﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL.Utils;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using DAL.DataSet;
using DAL.Entity;
using DAL.Models;
using DAL.Persistencia;
using NewTierra.Reports;

namespace NewTierra.Pages.Operacoes
{
    public partial class QuoteConsultaNew : System.Web.UI.Page
    {
        public static string statusGroup;
        public static string statusFiltros;
        public static string statusDataListHoteisTarifas;
        public static string statusServExtra;
        public static int CountIn;
        public static string divQuoteShow;
        public static int IdCidadeHotel;
        public static int VerificaQuote = 0;
        public static int VerificaFile;
        public static int flagTC = 0;

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                ViewState["QuoteAtiva"] = "0";

                if (Session["FileCriado"] != null)
                {
                    lblMsgCadQuotatio.Text = Session["FileCriado"].ToString();
                    Session["FileCriado"] = null;
                }

                if (ConfigurationManager.AppSettings["FilePuxaMarkup"].ToString().Equals("Y")) ViewState["PuxaMarkupStt"] = 1; else ViewState["PuxaMarkupStt"] = 0;

                PopularDrops();
                PopularDropsFiltro();

                PegaUsuario(sender, e);

                lblDataNow.Text = string.Format("{0:dd MMM yyyy}", DateTime.Now);

                txtQuoteNumber.Focus();
                statusGroup = "none";
                statusFiltros = "block";
                statusDataListHoteisTarifas = "none";
                statusServExtra = "none";
                divQuoteShow = "block";
                CountIn = 0;
                VerificaQuote = 0;
                //txtQuoteCode.Text = DateTime.Now.ToString("yyyyMMMdd");

                ViewState["VerificaLodge"] = 0;

                //VisivelPanel(1);                
            }
        }

        private Usuario ReadCookiesUser()
        {
            if (Request.Cookies["UsuarioNewTierra"]["id"] != null)
            {
                string userSettings = Request.Cookies["UsuarioNewTierra"]["id"];
                var usuario = new UsuarioDAL().ObterPorId(Convert.ToInt32(userSettings));

                Session["LoggedUser"] = usuario.US_id;
                //Session["user"] = Request.Cookies["UserChat"]["id"];
                //Response.Redirect("index.aspx", false);
                return usuario;
            }
            else
            {
                return null;
            }
        }

        #region Popular Dados

        protected void PopularDrops()
        {
            PopularDropTipoTarifa();
            PopularDropCliente();
            PopularDropLinguagem();
            PopularDropMoeda();
            PopularDropADL();
            PopularDropCHD();
            PopularDropINF();
            PopularDropStatus();
            PopularDropCidadeHotel();
            PopularDropHoteisFiltro();
            //PopulaDropCidadeTransFiltro();
            PopularDropNumPaxsTransfers();
            //PopulaDropCidadeToursFiltro();
            PopularDropNumPaxsTours();
            PopularddlTipoServExtra();
            PopularDropCidadeFlights();
            PopulaDropCategoriaHoteltarifaVazia();
            PopulaDropRoomAddTarifaHotelVazia();
            PopulaDropMoedaAddTafiaHotelVazia();
            PopularDropClienteSelectFileCopia();
            PopularDropUsuarioSelectFileCopia();
            PopulaCategoriaHoteis();
        }

        protected void PopularDropsFiltro()
        {
            PopularDropClienteFiltro();
            PopularDropUsuariosFiltro();
            PopularDropUsuarios();
        }

        protected void PopularDropTipoTarifa()
        {
            try
            {
                MercadoTipoTarifaDAL td = new MercadoTipoTarifaDAL();

                ddlTipoTarifa.DataSource = td.ListarTodos();
                ddlTipoTarifa.DataTextField = "S_mercado_tipo_tarifa_nome";
                ddlTipoTarifa.DataValueField = "S_mercado_tipo_tarifa_id";
                ddlTipoTarifa.DataBind();

                ddlTipoTarifa.Items.Insert(0, new ListItem("Selecione", "0"));
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopularDropCliente()
        {
            try
            {
                ClienteDAL cd = new ClienteDAL();

                ddlCliente.DataSource = cd.ListarTodos();
                ddlCliente.DataValueField = "Cliente_id";
                ddlCliente.DataTextField = "Cliente_nome";
                ddlCliente.DataBind();

                ddlCliente.Items.Insert(0, new ListItem("Selecione", "0"));
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopularDropUsuarios()
        {
            try
            {
                UsuarioDAL ud = new UsuarioDAL();

                ddlUsuario.DataSource = ud.ListarTodos();
                ddlUsuario.DataValueField = "US_id";
                ddlUsuario.DataTextField = "US_nome";
                ddlUsuario.DataBind();

                ddlUsuario.Items.Insert(0, new ListItem("Selecione", "0"));
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopularDropClienteFiltro()
        {
            try
            {
                ClienteDAL cd = new ClienteDAL();

                ddlClienteFiltro.DataSource = cd.ListarTodos();
                ddlClienteFiltro.DataValueField = "Cliente_id";
                ddlClienteFiltro.DataTextField = "Cliente_nome";
                ddlClienteFiltro.DataBind();

                ddlClienteFiltro.Items.Insert(0, new ListItem("Selecione", "0"));

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopularDropUsuariosFiltro()
        {
            try
            {
                UsuarioDAL ud = new UsuarioDAL();

                ddlUsuarioFiltro.DataSource = ud.ListarTodos();
                ddlUsuarioFiltro.DataValueField = "US_id";
                ddlUsuarioFiltro.DataTextField = "US_nome";
                ddlUsuarioFiltro.DataBind();

                ddlUsuarioFiltro.Items.Insert(0, new ListItem("Selecione", "0"));
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopularDropLinguagem()
        {
            try
            {
                FLinguagemDAL fl = new FLinguagemDAL();

                ddlLinguagem.DataSource = fl.ListarTodos();
                ddlLinguagem.DataValueField = "FLinguagem_id";
                ddlLinguagem.DataTextField = "FLinguagem_nome";
                ddlLinguagem.DataBind();

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopularDropMoeda()
        {
            try
            {
                MoedaDAL fl = new MoedaDAL();

                ddlMoeda.DataSource = fl.ListarTodos();
                ddlMoeda.DataValueField = "Moeda_id";
                ddlMoeda.DataTextField = "Moeda_nome";
                ddlMoeda.DataBind();

                //ddlMoeda.Items.Insert(0, new ListItem("Selecione", "0"));
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopularDropStatus()
        {
            try
            {
                QGStatusDAL fl = new QGStatusDAL();

                ddlStatus.DataSource = fl.ListarTodos();
                ddlStatus.DataValueField = "Quotation_status_id";
                ddlStatus.DataTextField = "Quotation_status_nome";
                ddlStatus.DataBind();

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopularDropCidadeHotel()
        {
            try
            {
                CidadeDAL fl = new CidadeDAL();

                //ddlCidadeHotel.DataSource = fl.ListarTodos().OrderBy(c => c.CID_nome);
                //ddlCidadeHotel.DataValueField = "CID_id";
                //ddlCidadeHotel.DataTextField = "CID_nome";
                //ddlCidadeHotel.DataBind();

                //ddlCidadeHotel.Items.Insert(0, new ListItem("Selecione...", "0"));
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void ddlCidadeHotel_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopularDropHoteisFiltro();

            lblPaxsHoteis.Visible = false;
            lblEstacaoHoteis.Visible = false;
            ddlPaxsHoteis.Visible = false;
            ddlEstacoesHoteis.Visible = false;

            DataListHoteis.DataBind();
        }

        protected void PopularDropHoteisFiltro()
        {
            try
            {
                SupplierDAL fl = new SupplierDAL();

                ddlHoteisFiltro.DataSource = fl.ListarTodos(1, Convert.ToInt32(ViewState["IdCidadeHotel"])).OrderBy(s => s.S_nome);
                ddlHoteisFiltro.DataValueField = "S_id";
                ddlHoteisFiltro.DataTextField = "S_nome";
                ddlHoteisFiltro.DataBind();

                ddlHoteisFiltro.Items.Insert(0, new ListItem("Selecione...", "0"));

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void ddlHoteisFiltro_SelectedIndexChanged(object sender, EventArgs e)
        {
            //PopulaDropSelectFDS();
            //PopulaDropTipoRoom();
            VerificaLodgeHotel();
        }

        int VerificaLodgeHotel()
        {
            try
            {

                SBasesDAL sbd = new SBasesDAL();
                SupplierDAL sd = new SupplierDAL();

                if (sbd.ObterPorIdSupplier(Convert.ToInt32(ddlHoteisFiltro.SelectedValue)).Count != 0)
                {
                    lblPaxsHoteis.Visible = true;
                    ddlPaxsHoteis.Visible = true;

                    lblEstacaoHoteis.Visible = true;
                    ddlEstacoesHoteis.Visible = true;

                    PopularDropEstacoesHoteis();
                    PopularDropNumPaxsHoteis();

                    DataListHoteis.DataBind();

                    return 2;
                }
                else
                {

                    if (sd.VerificaLodge(Convert.ToInt32(ddlHoteisFiltro.SelectedValue)))
                    {
                        ddlEstacoesHoteis.Visible = true;
                        PopularDropEstacoesHoteis();

                        lblPaxsHoteis.Visible = false;
                        ddlPaxsHoteis.Visible = false;

                        DataListHoteis.DataBind();

                        return 1;
                    }

                    lblPaxsHoteis.Visible = false;
                    ddlPaxsHoteis.Visible = false;

                    lblEstacaoHoteis.Visible = false;
                    ddlEstacoesHoteis.Visible = false;

                    DataListHoteis.DataBind();

                    return 3;
                }


            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
                return 0;
            }
        }

        protected void ddlEstacoesHoteis_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataListHoteis.DataBind();
        }

        protected void ddlPaxsHoteis_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataListHoteis.DataBind();
        }

        protected void PopularDropCidadeFlights()
        {
            try
            {
                CidadeDAL fl = new CidadeDAL();

                ddlCidadeFlights.DataSource = fl.ListarTodos();
                ddlCidadeFlights.DataValueField = "CID_id";
                ddlCidadeFlights.DataTextField = "CID_cod_Iata";
                ddlCidadeFlights.DataBind();

                ddlCidadeFlights.Items.Insert(0, new ListItem("Selecione", "0"));
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        int RetornaUltimaOrdem(int IdFile)
        {
            try
            {

                FileTarifasDAL ftd = new FileTarifasDAL();
                FileTransfersDAL ftrd = new FileTransfersDAL();
                FileServExtraDAL fsed = new FileServExtraDAL();

                List<int> lista = new List<int>();

                lista.Add(ftd.RetornaUltimaOrdem(IdFile));
                lista.Add(ftrd.RetornaUltimaOrdem(IdFile));
                lista.Add(ftrd.RetornaUltimaOrdem(IdFile));

                return lista.Max();

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
                return 0;
            }
        }

        protected void PopulaDataListHoteis()
        {
            try
            {
                SupplierDAL sd = new SupplierDAL();
                FotoDAL fd = new FotoDAL();
                SBasesDAL sbd = new SBasesDAL();

                DayOfWeek DiaF = Convert.ToDateTime(txtDataPeriodoInHotel.Text).DayOfWeek;
                DayOfWeek DiaO = Convert.ToDateTime(txtDataPeriodoOutHotel.Text).DayOfWeek;
                DayOfWeek DiaN = DateTime.Now.DayOfWeek;

                string datefm = Convert.ToDateTime(txtDataPeriodoInHotel.Text).ToString("yyyyMMdd");
                string datefmtrat = "'" + datefm + "'";
                string dateout = Convert.ToDateTime(txtDataPeriodoOutHotel.Text).ToString("yyyyMMdd");
                string dateouttrat = "'" + dateout + "'";

                string[] pars = ConfigurationManager.ConnectionStrings["NewTierraEntities"].ToString().Split('\"');
                SqlConnection Con = new SqlConnection(pars[1]);
                string sql;

                Con.Open();

                sql = "SELECT DISTINCT S_Mercado_Tarifa.S_merc_tarif_porApartamento, Tipo_Room.Tipo_room_number, Supplier.S_id, Supplier.S_nome, Supplier.S_endereco, Supplier.S_telefone, Tipo_Room.Tipo_room_nome, Tarif_Categoria.Tarif_categoria_nome, ";
                sql = sql + "Tarif_Categoria.Tarif_categoria_id, S_Mercado_Tarifa.S_merc_tarif_tarifa_total, S_Mercado_Periodo.S_merc_periodo_from, S_Mercado_Periodo.S_merc_periodo_to, ";
                sql = sql + "S_Mercado_Periodo.S_merc_periodo_fdsFrom, S_Mercado_Periodo.S_merc_periodo_fdsTo, Moeda.Moeda_sigla, S_Mercado_Estacao.S_mercado_estacao_nome, S_Mercado_Periodo.Pacote_nome";

                if (sbd.ObterPorIdSupplier(Convert.ToInt32(ddlHoteisFiltro.SelectedValue)).Count != 0)
                {
                    sql = sql + ", S_Bases.Base_de, S_Bases.Base_ate ";
                }

                sql = sql + " FROM S_Mercado_Tarifa INNER JOIN S_Mercado_Periodo ON S_Mercado_Tarifa.S_merc_periodo_id = S_Mercado_Periodo.S_merc_periodo_id INNER JOIN ";
                sql = sql + "Supplier ON S_Mercado_Periodo.S_id = Supplier.S_id INNER JOIN Tipo_Room ON S_Mercado_Tarifa.Tipo_room_id = Tipo_Room.Tipo_room_id INNER JOIN ";
                sql = sql + "Tarif_Categoria ON S_Mercado_Tarifa.Tarif_categoria_id = Tarif_Categoria.Tarif_categoria_id INNER JOIN Moeda ON S_Mercado_Periodo.Moeda_id = Moeda.Moeda_id INNER JOIN ";
                sql = sql + "S_Mercado_Estacao ON S_Mercado_Periodo.S_mercado_estacao_id = S_Mercado_Estacao.S_mercado_estacao_id ";

                sql = sql + "INNER JOIN S_Categoria ON Supplier.Categ_id = S_Categoria.Categ_id ";

                //sql = sql + "LEFT OUTER JOIN S_Image ON Supplier.S_id = S_Image.S_id ";

                if (sbd.ObterPorIdSupplier(Convert.ToInt32(ddlHoteisFiltro.SelectedValue)).Count != 0)
                {
                    sql = sql + "INNER JOIN S_Bases ON Supplier.S_id = S_Bases.S_id AND Moeda.Moeda_id = S_Bases.Moeda_id INNER JOIN ";
                    sql = sql + "S_Tarifa_Base ON S_Mercado_Tarifa.S_merc_tarif_id = S_Tarifa_Base.S_merc_tarif_id AND S_Bases.Base_id = S_Tarifa_Base.Base_id ";
                }

                sql = sql + "WHERE (S_Mercado_Periodo.S_merc_periodo_from <= " + datefmtrat + ") AND (S_Mercado_Periodo.S_merc_periodo_to >= " + dateouttrat + ") AND (Tipo_Room.Tipo_room_id = 2) ";

                if (Convert.ToInt32(ViewState["IdCidadeHotel"]) != 0)
                {
                    sql = sql + " AND (Supplier.CID_id = " + Convert.ToInt32(ViewState["IdCidadeHotel"]) + ") ";
                }

                //if (fd.ObterPorSupplierCapa(Convert.ToInt32(ddlHoteisFiltro.SelectedValue)) != null || !txtAutoHoteis.Text.Equals(""))
                //{
                //sql = sql + " AND (S_Image.Image_capa = 'S') ";
                //}

                if (sd.VerificaLodge(Convert.ToInt32(ddlHoteisFiltro.SelectedValue)))
                {
                    sql = sql + "AND (S_Mercado_Estacao.S_mercado_estacao_id = " + Convert.ToInt32(ddlEstacoesHoteis.SelectedValue) + ") ";
                }

                if (!ddlHoteisFiltro.SelectedValue.Equals("0"))
                {
                    sql = sql + "AND (Supplier.S_id = " + Convert.ToInt32(ddlHoteisFiltro.SelectedValue) + ") ";

                    if (sbd.ObterPorIdSupplier(Convert.ToInt32(ddlHoteisFiltro.SelectedValue)).Count != 0)
                    {
                        sql = sql + "AND (S_Bases.Base_de <= " + Convert.ToInt32(ddlPaxsHoteis.SelectedValue) + ") AND (S_Bases.Base_ate >= " + Convert.ToInt32(ddlPaxsHoteis.SelectedValue) + ") ";
                        sql = sql + "AND (S_Mercado_Estacao.S_mercado_estacao_id = " + Convert.ToInt32(ddlEstacoesHoteis.SelectedValue) + ")";
                    }
                }

                if (!txtAutoHoteis.Text.Equals(""))
                {
                    sql = sql + " AND (Supplier.S_nome = '" + txtAutoHoteis.Text + "') ";
                }

                if (!ddlCategoriaHoteis.SelectedValue.Equals("0"))
                {
                    sql = sql + " AND (Supplier.Categ_id = " + Convert.ToInt32(ddlCategoriaHoteis.SelectedValue) + ") ";
                }

                //------------------- Começa OR -------------------------------

                sql = sql + " OR (S_Mercado_Periodo.S_merc_periodo_from <= " + dateouttrat + ") AND (S_Mercado_Periodo.S_merc_periodo_to >= " + datefmtrat + ") AND (Tipo_Room.Tipo_room_id = 2) ";
                //sql = sql + "(Supplier.CID_id = " + Convert.ToInt32(ddlCidadeHotel.SelectedValue) + ") ";

                if (Convert.ToInt32(ViewState["IdCidadeHotel"]) != 0)
                {
                    sql = sql + " AND (Supplier.CID_id = " + Convert.ToInt32(ViewState["IdCidadeHotel"]) + ") ";
                }

                //if (fd.ObterPorSupplierCapa(Convert.ToInt32(ddlHoteisFiltro.SelectedValue)) != null || !txtAutoHoteis.Text.Equals(""))
                //{
                //sql = sql + " AND (S_Image.Image_capa = 'S') ";
                //}

                if (sd.VerificaLodge(Convert.ToInt32(ddlHoteisFiltro.SelectedValue)))
                {
                    sql = sql + "AND (S_Mercado_Estacao.S_mercado_estacao_id = " + Convert.ToInt32(ddlEstacoesHoteis.SelectedValue) + ") ";
                }

                if (!ddlHoteisFiltro.SelectedValue.Equals("0"))
                {
                    sql = sql + "AND (Supplier.S_id = " + Convert.ToInt32(ddlHoteisFiltro.SelectedValue) + ") ";

                    if (sbd.ObterPorIdSupplier(Convert.ToInt32(ddlHoteisFiltro.SelectedValue)).Count != 0)
                    {
                        sql = sql + "AND (S_Bases.Base_de <= " + Convert.ToInt32(ddlPaxsHoteis.SelectedValue) + ") AND (S_Bases.Base_ate >= " + Convert.ToInt32(ddlPaxsHoteis.SelectedValue) + ") ";
                        sql = sql + "AND (S_Mercado_Estacao.S_mercado_estacao_id = " + Convert.ToInt32(ddlEstacoesHoteis.SelectedValue) + ")";
                    }
                }

                if (!txtAutoHoteis.Text.Equals(""))
                {
                    sql = sql + " AND (Supplier.S_nome = '" + txtAutoHoteis.Text + "') ";
                }

                if (!ddlCategoriaHoteis.SelectedValue.Equals("0"))
                {
                    sql = sql + " AND (Supplier.Categ_id = " + Convert.ToInt32(ddlCategoriaHoteis.SelectedValue) + ") ";
                }

                SqlCommand cmd = new SqlCommand(sql, Con);
                SqlDataReader reader = cmd.ExecuteReader();

                DataTable dummy = new DataTable();
                dummy.Columns.Add("S_id");
                //dummy.Columns.Add("Image_nome");
                dummy.Columns.Add("S_nome");
                dummy.Columns.Add("S_endereco");
                dummy.Columns.Add("S_telefone");
                dummy.Columns.Add("Moeda_sigla");
                dummy.Columns.Add("Pacote_nome");
                dummy.Columns.Add("S_merc_tarif_tarifa_total");
                dummy.Columns.Add("Tipo_room_nome");
                dummy.Columns.Add("Tarif_categoria_nome");
                dummy.Columns.Add("Tarif_categoria_id");
                dummy.Columns.Add("S_mercado_estacao_nome");
                dummy.Columns.Add("S_merc_periodo_from");
                dummy.Columns.Add("S_merc_periodo_to");
                dummy.Columns.Add("S_merc_periodo_fdsFrom");
                dummy.Columns.Add("S_merc_periodo_fdsTo");
                dummy.Columns.Add("ImgUrl");
                dummy.Columns.Add("S_merc_tarif_porApartamento");
                dummy.Columns.Add("Tipo_room_number");

                while (reader.Read())
                {

                    if (reader["S_merc_periodo_fdsFrom"].ToString() == "")
                    {
                        DataRow dw = dummy.NewRow();

                        S_Image si = fd.ObterPorSupplierCapa(Convert.ToInt32(reader["S_id"]));

                        if (si == null)
                        {
                            dw["ImgUrl"] = "~/Galeria/semimagem.jpg";
                        }
                        else
                        {
                            dw["ImgUrl"] = "~/Galeria/" + reader["S_id"] + "/" + si.Image_nome;
                        }

                        dw["S_id"] = reader["S_id"].ToString();

                        //dw["Image_nome"] = reader["Image_nome"].ToString();

                        dw["S_nome"] = reader["S_nome"].ToString();
                        dw["S_endereco"] = reader["S_endereco"].ToString();
                        dw["S_telefone"] = reader["S_telefone"].ToString();
                        dw["Moeda_sigla"] = reader["Moeda_sigla"].ToString();
                        dw["S_merc_tarif_tarifa_total"] = reader["S_merc_tarif_tarifa_total"].ToString();
                        dw["Tipo_room_nome"] = reader["Tipo_room_nome"].ToString();
                        dw["Tarif_categoria_nome"] = reader["Tarif_categoria_nome"].ToString();
                        dw["Tarif_categoria_id"] = reader["Tarif_categoria_id"].ToString();
                        dw["S_mercado_estacao_nome"] = reader["S_mercado_estacao_nome"].ToString();
                        dw["S_merc_periodo_from"] = string.Format("{0:dd/MM/yyyy}", reader["S_merc_periodo_from"]);
                        dw["S_merc_periodo_to"] = string.Format("{0:dd/MM/yyyy}", reader["S_merc_periodo_to"]);
                        dw["S_merc_periodo_fdsFrom"] = reader["S_merc_periodo_fdsFrom"].ToString();
                        dw["S_merc_periodo_fdsTo"] = reader["S_merc_periodo_fdsTo"].ToString();
                        dw["Pacote_nome"] = reader["Pacote_nome"].ToString();
                        dw["S_merc_tarif_porApartamento"] = reader["S_merc_tarif_porApartamento"].ToString();
                        dw["Tipo_room_number"] = reader["Tipo_room_number"].ToString();

                        dummy.Rows.Add(dw);
                    }
                    else
                    {

                        DayOfWeek teste01 = ReturnDayPT(reader["S_merc_periodo_fdsFrom"].ToString());
                        DayOfWeek teste02 = ReturnDayPT(reader["S_merc_periodo_fdsTo"].ToString());

                        bool SemanaIn = IsBetween(ReturnDayPT(reader["S_merc_periodo_fdsFrom"].ToString()), ReturnDayPT(reader["S_merc_periodo_fdsTo"].ToString()), Convert.ToDateTime(txtDataPeriodoInHotel.Text).DayOfWeek);
                        bool SemanaOut;

                        if (ReturnDayPT(reader["S_merc_periodo_fdsFrom"].ToString()) == Convert.ToDateTime(txtDataPeriodoOutHotel.Text).DayOfWeek)
                        {
                            SemanaOut = false;
                        }
                        else
                        {
                            SemanaOut = IsBetween(ReturnDayPT(reader["S_merc_periodo_fdsFrom"].ToString()), ReturnDayPT(reader["S_merc_periodo_fdsTo"].ToString()), Convert.ToDateTime(txtDataPeriodoOutHotel.Text).DayOfWeek);
                        }

                        if (SemanaIn || SemanaOut)
                        {
                            DataRow dw = dummy.NewRow();

                            S_Image si = fd.ObterPorSupplierCapa(Convert.ToInt32(reader["S_id"]));

                            if (si == null)
                            {
                                dw["ImgUrl"] = "~/Galeria/semimagem.jpg";
                            }
                            else
                            {
                                dw["ImgUrl"] = "~/Galeria/" + reader["S_id"] + "/" + si.Image_nome;
                            }

                            dw["S_id"] = reader["S_id"].ToString();

                            //dw["Image_nome"] = reader["Image_nome"].ToString();

                            dw["S_nome"] = reader["S_nome"].ToString();
                            dw["S_endereco"] = reader["S_endereco"].ToString();
                            dw["S_telefone"] = reader["S_telefone"].ToString();
                            dw["Moeda_sigla"] = reader["Moeda_sigla"].ToString();
                            dw["S_merc_tarif_tarifa_total"] = reader["S_merc_tarif_tarifa_total"].ToString();
                            dw["Tipo_room_nome"] = reader["Tipo_room_nome"].ToString();
                            dw["Tarif_categoria_nome"] = reader["Tarif_categoria_nome"].ToString();
                            dw["Tarif_categoria_id"] = reader["Tarif_categoria_id"].ToString();
                            dw["S_mercado_estacao_nome"] = reader["S_mercado_estacao_nome"].ToString();
                            dw["S_merc_periodo_from"] = string.Format("{0:dd/MM/yyyy}", reader["S_merc_periodo_from"]);
                            dw["S_merc_periodo_to"] = string.Format("{0:dd/MM/yyyy}", reader["S_merc_periodo_to"]);
                            dw["S_merc_periodo_fdsFrom"] = reader["S_merc_periodo_fdsFrom"].ToString();
                            dw["S_merc_periodo_fdsTo"] = reader["S_merc_periodo_fdsTo"].ToString();
                            dw["Pacote_nome"] = reader["Pacote_nome"].ToString();
                            dw["S_merc_tarif_porApartamento"] = reader["S_merc_tarif_porApartamento"].ToString();
                            dw["Tipo_room_number"] = reader["Tipo_room_number"].ToString();

                            dummy.Rows.Add(dw);
                        }

                    }
                }

                Con.Close();

                //DataListHoteis.DataSource = sd.ListarTodos(Convert.ToDateTime(txtDataPeriodoInHotel.Text), Convert.ToDateTime(txtDataPeriodoOutHotel.Text), Convert.ToInt32(ddlCidadeHotel.SelectedValue), Convert.ToInt32(ddlHoteisFiltro.SelectedValue));
                //DataListHoteis.DataBind();

                if (dummy.Rows.Count == 0)
                {
                    ShowAddTarifaVazia.Visible = true;
                }
                else
                {
                    ShowAddTarifaVazia.Visible = false;
                }

                DataListHoteis.DataSource = dummy;
                DataListHoteis.DataBind();

                //PopulaQuatorsHoteis();

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        bool IsBetween(DayOfWeek min, DayOfWeek max, DayOfWeek toCheck)
        {
            if (min <= max)
                return toCheck >= min && toCheck <= max;

            return toCheck >= min || toCheck <= max;
        }

        public string UppercaseFirst(string s)
        {
            return char.ToUpper(s[0]) + s.Substring(1);
        }

        public DayOfWeek ReturnDay(string day)
        {
            switch (day)
            {
                case "Monday":
                    return DayOfWeek.Monday;
                case "Tuesday":
                    return DayOfWeek.Tuesday;
                case "Wednesday":
                    return DayOfWeek.Wednesday;
                case "Thursday":
                    return DayOfWeek.Thursday;
                case "Friday":
                    return DayOfWeek.Friday;
                case "Saturday":
                    return DayOfWeek.Saturday;
                case "Sunday":
                    return DayOfWeek.Sunday;
                default:
                    return DayOfWeek.Sunday;
            }
        }

        public DayOfWeek ReturnDayPT(string day)
        {
            switch (day)
            {
                case "Seg":
                    return DayOfWeek.Monday;
                case "Ter":
                    return DayOfWeek.Tuesday;
                case "Qua":
                    return DayOfWeek.Wednesday;
                case "Qui":
                    return DayOfWeek.Thursday;
                case "Sex":
                    return DayOfWeek.Friday;
                case "Sab":
                    return DayOfWeek.Saturday;
                case "Dom":
                    return DayOfWeek.Sunday;
                default:
                    return DayOfWeek.Sunday;
            }
        }

        public DayOfWeek ReturnDayNext(string day)
        {
            switch (day)
            {
                case "Seg":
                    return DayOfWeek.Tuesday;
                case "Ter":
                    return DayOfWeek.Wednesday;
                case "Qua":
                    return DayOfWeek.Thursday;
                case "Qui":
                    return DayOfWeek.Friday;
                case "Sex":
                    return DayOfWeek.Saturday;
                case "Sab":
                    return DayOfWeek.Sunday;
                case "Dom":
                    return DayOfWeek.Monday;
                default:
                    return DayOfWeek.Sunday;
            }
        }

        protected void PopulaQuatorsHoteis()
        {
            try
            {

                foreach (DataListItem item in DataListHoteis.Items)
                {
                    TarifaDAL td = new TarifaDAL();

                    DataList DataListHoteisTarifas = (DataList)item.FindControl("DataListHoteisTarifas");
                    Label lblSuplID = (Label)item.FindControl("lblSuplID");
                    Label lblQuartoID = (Label)item.FindControl("lblQuartoID");
                    Label lblFDS = (Label)item.FindControl("lblFDS");

                    string[] pars = lblFDS.Text.Split('/');


                    DataListHoteisTarifas.DataSource = td.ListarTodosHoteisTarifasLodge(Convert.ToDateTime(txtDataPeriodoInHotel.Text), Convert.ToDateTime(txtDataPeriodoOutHotel.Text), Convert.ToInt32(lblSuplID.Text), Convert.ToInt32(lblQuartoID.Text), Convert.ToInt32(ddlPaxsHoteis.SelectedValue), Convert.ToInt32(ddlEstacoesHoteis.SelectedValue), pars[0].Trim());
                    DataListHoteisTarifas.DataBind();


                    //    DataListHoteisTarifas.DataSource = td.ListarTodosHoteisTarifas(Convert.ToDateTime(txtDataPeriodoInHotel.Text), Convert.ToDateTime(txtDataPeriodoOutHotel.Text), Convert.ToInt32(lblSuplID.Text), Convert.ToInt32(lblQuartoID.Text), pars[0].Trim());
                    //  DataListHoteisTarifas.DataBind();

                }

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void DataListHoteis_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            try
            {

                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    TarifaDAL td = new TarifaDAL();
                    SBasesDAL sbd = new SBasesDAL();
                    MealDAL md = new MealDAL();

                    DataList DataListHoteisTarifas = (DataList)e.Item.FindControl("DataListHoteisTarifas");
                    DataList DataListHoteisMeals = (DataList)e.Item.FindControl("DataListHoteisMeals");
                    Label lblSuplID = (Label)e.Item.FindControl("lblSuplID");
                    Label lblQuartoID = (Label)e.Item.FindControl("lblQuartoID");
                    Label lblFDS = (Label)e.Item.FindControl("lblFDS");
                    Label lblNomePacote = (Label)e.Item.FindControl("lblNomePacote");
                    Label lblEstacao = (Label)e.Item.FindControl("lblEstacao");
                    Label lblFrom = (Label)e.Item.FindControl("lblFrom");
                    Label lblTo = (Label)e.Item.FindControl("lblTo");


                    string[] pars = lblFDS.Text.Split('/');

                    //string[] pacote = new string[2];

                    //if (!lblNomePacote.Text.Equals(""))
                    //{
                    //    pacote = lblNomePacote.Text.Split(':');
                    //}
                    //else
                    //{
                    //    pacote[1] = "";
                    //}

                    //string[] estacao = lblEstacao.Text.Split(':');
                    //lblEstacao.Text = estacao[1].Trim();

                    if (ddlPaxsHoteis.SelectedValue != "")
                    {
                        DataListHoteisMeals.DataSource = md.ListarMealsPorPH(Convert.ToInt32(lblSuplID.Text), Convert.ToDateTime(lblFrom.Text),
                                                                             Convert.ToDateTime(lblTo.Text), lblEstacao.Text, Convert.ToInt32(ddlPaxsHoteis.SelectedValue), lblNomePacote.Text);
                    }
                    else
                    {
                        DataListHoteisMeals.DataSource = md.ListarMealsPorPH(Convert.ToInt32(lblSuplID.Text), Convert.ToDateTime(lblFrom.Text),
                                                                             Convert.ToDateTime(lblTo.Text), lblEstacao.Text, pars[0].ToString().Trim(), lblNomePacote.Text);
                    }

                    DataListHoteisMeals.DataBind();

                    if (sbd.ObterPorIdSupplier(Convert.ToInt32(ddlHoteisFiltro.SelectedValue)).Count != 0)
                    {

                        string datefm = Convert.ToDateTime(txtDataPeriodoInHotel.Text).ToString("yyyyMMdd");
                        string datefmtrat = "'" + datefm + "'";
                        string dateout = Convert.ToDateTime(txtDataPeriodoOutHotel.Text).ToString("yyyyMMdd");
                        string dateouttrat = "'" + dateout + "'";

                        SqlCon Con = new SqlCon();

                        Con.AbrirConexao();

                        string sql = "";
                        sql = sql + "SELECT S_Mercado_Tarifa.S_merc_tarif_id, Moeda.Moeda_id, Moeda.Moeda_sigla, Supplier.S_id, Tipo_Room.Tipo_room_id, Supplier.S_email, S_Mercado_Tarifa.S_merc_tarif_tarifa_total, S_Mercado_Periodo.S_merc_periodo_from, S_Mercado_Periodo.S_merc_periodo_to, Supplier.S_nome, ";
                        sql = sql + "S_Bases.Base_de, S_Bases.Base_ate, S_Tarifa_Base.Base_id, Tipo_Room.Tipo_room_nome, Tarif_Categoria.Tarif_categoria_nome, Tarif_Categoria.Tarif_categoria_id, S_Mercado_Tarifa_Status.S_mercado_tarifa_status_nome,  S_Mercado_Tarifa.S_merc_tarif_porApartamento, Tipo_Room.Tipo_room_number ";
                        sql = sql + "FROM S_Mercado_Periodo INNER JOIN S_Mercado_Tarifa ON S_Mercado_Periodo.S_merc_periodo_id = S_Mercado_Tarifa.S_merc_periodo_id INNER JOIN ";
                        sql = sql + "Supplier ON S_Mercado_Periodo.S_id = Supplier.S_id INNER JOIN S_Mercado_Estacao ON S_Mercado_Periodo.S_mercado_estacao_id = S_Mercado_Estacao.S_mercado_estacao_id INNER JOIN ";
                        sql = sql + "S_Bases ON Supplier.S_id = S_Bases.S_id INNER JOIN S_Tarifa_Base ON S_Mercado_Tarifa.S_merc_tarif_id = S_Tarifa_Base.S_merc_tarif_id AND S_Bases.Base_id = S_Tarifa_Base.Base_id INNER JOIN ";
                        sql = sql + "Tipo_Room ON S_Mercado_Tarifa.Tipo_room_id = Tipo_Room.Tipo_room_id INNER JOIN Tarif_Categoria ON S_Mercado_Tarifa.Tarif_categoria_id = Tarif_Categoria.Tarif_categoria_id INNER JOIN Moeda ON S_Mercado_Periodo.Moeda_id = Moeda.Moeda_id LEFT OUTER JOIN ";
                        sql = sql + "S_Mercado_Tarifa_Status ON S_Mercado_Tarifa.S_merc_tarif_status_id = S_Mercado_Tarifa_Status.S_mercado_tarifa_status_id ";

                        sql = sql + "WHERE (S_Mercado_Periodo.S_merc_periodo_from <= " + datefmtrat + ") AND (S_Mercado_Periodo.S_merc_periodo_to >= " + dateouttrat + ") AND (Supplier.S_id = " + Convert.ToInt32(lblSuplID.Text) + ") AND ";
                        sql = sql + "(S_Mercado_Estacao.S_mercado_estacao_id = " + Convert.ToInt32(ddlEstacoesHoteis.SelectedValue) + ") AND (S_Bases.Base_de <= " + Convert.ToInt32(ddlPaxsHoteis.SelectedValue) + ") AND (S_Bases.Base_ate >= " + Convert.ToInt32(ddlPaxsHoteis.SelectedValue) + ") AND (S_Mercado_Tarifa.Tarif_categoria_id = " + Convert.ToInt32(lblQuartoID.Text) + ") ORDER BY Tipo_Room.Tipo_room_number";

                        Con.Cmd = new SqlCommand(sql, Con.Con);
                        Con.Dr = Con.Cmd.ExecuteReader();

                        DataTable dummy = new DataTable();
                        dummy.Columns.Add("Tarif_categoria_nome");
                        dummy.Columns.Add("Tarif_categoria_id");
                        dummy.Columns.Add("Tipo_room_nome");
                        dummy.Columns.Add("Tipo_room_id");
                        dummy.Columns.Add("S_id");
                        dummy.Columns.Add("EmailSupplier");
                        dummy.Columns.Add("Moeda_id");
                        dummy.Columns.Add("Moeda_sigla");
                        dummy.Columns.Add("S_merc_tarif_tarifa_total");
                        dummy.Columns.Add("S_merc_tarif_id");
                        dummy.Columns.Add("S_mercado_tarifa_status_nome");
                        dummy.Columns.Add("S_merc_tarif_porApartamento");
                        dummy.Columns.Add("Tipo_room_number");

                        while (Con.Dr.Read())
                        {
                            DataRow dw = dummy.NewRow();

                            dw["Tarif_categoria_nome"] = Con.Dr["Tarif_categoria_nome"].ToString();
                            dw["Tarif_categoria_id"] = Con.Dr["Tarif_categoria_id"].ToString();
                            dw["Tipo_room_nome"] = Con.Dr["Tipo_room_nome"].ToString();
                            dw["Tipo_room_id"] = Con.Dr["Tipo_room_id"].ToString();
                            dw["S_id"] = Con.Dr["S_id"].ToString();
                            dw["EmailSupplier"] = Con.Dr["S_email"].ToString();
                            dw["Moeda_id"] = Con.Dr["Moeda_id"].ToString();
                            dw["Moeda_sigla"] = Con.Dr["Moeda_sigla"].ToString();
                            dw["S_merc_tarif_tarifa_total"] = Con.Dr["S_merc_tarif_tarifa_total"].ToString();
                            dw["S_merc_tarif_id"] = Con.Dr["S_merc_tarif_id"].ToString();
                            dw["S_mercado_tarifa_status_nome"] = Con.Dr["S_mercado_tarifa_status_nome"].ToString();

                            if (dw["S_merc_tarif_porApartamento"] == "")
                            {
                                dw["S_merc_tarif_porApartamento"] = null;
                            }
                            else
                            {
                                dw["S_merc_tarif_porApartamento"] = Con.Dr["S_merc_tarif_porApartamento"].ToString();
                            }

                            dw["Tipo_room_number"] = Con.Dr["Tipo_room_number"].ToString();

                            dummy.Rows.Add(dw);
                        }

                        DataListHoteisTarifas.DataSource = dummy;
                        DataListHoteisTarifas.DataBind();
                    }
                    else if (lblNomePacote.Text != "")
                    {
                        DataListHoteisTarifas.DataSource = td.ListarTodosHoteisTarifas(Convert.ToDateTime(lblFrom.Text), Convert.ToDateTime(lblTo.Text), Convert.ToInt32(lblSuplID.Text), Convert.ToInt32(lblQuartoID.Text), pars[0].Trim(), 1, lblEstacao.Text, lblNomePacote.Text);
                        DataListHoteisTarifas.DataBind();
                    }
                    else
                    {
                        DataListHoteisTarifas.DataSource = td.ListarTodosHoteisTarifas(Convert.ToDateTime(lblFrom.Text), Convert.ToDateTime(lblTo.Text), Convert.ToInt32(lblSuplID.Text), Convert.ToInt32(lblQuartoID.Text), pars[0].Trim(), 0, lblEstacao.Text, lblNomePacote.Text);
                        DataListHoteisTarifas.DataBind();
                    }


                    foreach (DataListItem item in DataListHoteisTarifas.Items)
                    {
                        SPoliticaCHDTarifasDAL spd = new SPoliticaCHDTarifasDAL();

                        Label lblIdTarifa = (Label)item.FindControl("lblIdTarifa");
                        int IdTarifa = Convert.ToInt32(lblIdTarifa.Text);
                        ImageButton OpenPoliticaCHD = (ImageButton)item.FindControl("OpenPoliticaCHD");

                        if (spd.ObterPorId(Convert.ToInt32(IdTarifa)) != null)
                        { OpenPoliticaCHD.ImageUrl = "~/images/Icones/politicaCHD.png"; }
                        else
                        { OpenPoliticaCHD.ImageUrl = "~/images/Icones/politicaCHDS.png"; }
                    }

                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopularDropADL()
        {
            try
            {
                for (int i = 1; i < 1001; i++)
                {
                    ListItem li = new ListItem();
                    li.Text = i.ToString();
                    li.Value = i.ToString();
                    ddlAdultos.Items.Add(li);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopularDropCHD()
        {
            try
            {
                for (int i = 0; i < 1001; i++)
                {
                    ListItem li = new ListItem();
                    li.Text = i.ToString();
                    li.Value = i.ToString();
                    ddlChd.Items.Add(li);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopularDropINF()
        {
            try
            {
                for (int i = 0; i < 1001; i++)
                {
                    ListItem li = new ListItem();
                    li.Text = i.ToString();
                    li.Value = i.ToString();
                    ddlInf.Items.Add(li);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopulaGridGroup()
        {
            try
            {
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();
                QuotationDAL qd = new QuotationDAL();

                //Quotation qt = qd.ObterPorId(Convert.ToInt32(txtQuoteNumber.Text));
                Quotation qt = qd.ObterPorCode(txtQuoteNumber.Text);

                GridGroups.DataSource = qgd.ListarTodos(qt.Quotation_Id);
                GridGroups.DataBind();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopularGridListCarrinho(int IdQuotGrupo)
        {
            try
            {

                FileCarrinhoDAL cd = new FileCarrinhoDAL();

                GridFileCarrinhoHoteis.DataSource = cd.MontaCarrinhoHoteis(IdQuotGrupo);
                GridFileCarrinhoHoteis.DataBind();

                //CalculaValorTotal();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void GridFileCarrinhoHoteis_DataBound(object sender, EventArgs e)
        {
            try
            {
                FileTarifasDAL ftd = new FileTarifasDAL();


                foreach (GridViewRow item in GridFileCarrinhoHoteis.Rows)
                {

                    Label lblValorTotalTarifas = (Label)item.FindControl("lblValorTotalTarifas");
                    TextBox txtQtdTarifas = (TextBox)item.FindControl("txtQtdTarifas");
                    TextBox txtValorTarifas = (TextBox)item.FindControl("txtValorTarifas");
                    Label lblMealStatus = (Label)item.FindControl("lblMealStatus");
                    Label lblNomeCidade = (Label)item.FindControl("lblNomeCidade");
                    Label lblNomeSupplier = (Label)item.FindControl("lblNomeSupplier");

                    TextBox txtMarkup = (TextBox)item.FindControl("txtMarkup");
                    TextBox txtDesconto = (TextBox)item.FindControl("txtDesconto");

                    TextBox txtVendaNet = (TextBox)item.FindControl("txtVendaNet");

                    TextBox txtVenda = (TextBox)item.FindControl("txtVenda");

                    TextBox txtMarkupNet = (TextBox)item.FindControl("txtMarkupNet");
                    TextBox txtDescontoNet = (TextBox)item.FindControl("txtDescontoNet");

                    Label lblPayingPax = (Label)item.FindControl("lblPayingPax");
                    Label lblNumNoites = (Label)item.FindControl("lblNumNoites");
                    Label IdFileTarifa = (Label)item.FindControl("IdFileTarifa");
                    Label lblStatus = (Label)item.FindControl("lblStatus");
                    ImageButton imgStatus = (ImageButton)item.FindControl("imgStatus");
                    ImageButton imgFlights = (ImageButton)item.FindControl("imgFlights");
                    ImageButton imgAtualizaCarrinhoTarifa = (ImageButton)item.FindControl("imgAtualizaCarrinhoTarifa");

                    CidadeDAL cidal = new CidadeDAL();

                    File_Tarifas ftt = ftd.ObterPorId(Convert.ToInt32(IdFileTarifa.Text));

                    lblNomeCidade.Text = cidal.ObterPorNomeSupplier(lblNomeSupplier.Text).CID_nome;

                    if (Convert.ToInt32(ViewState["PuxaMarkupStt"]) == 0)
                    {
                        txtVendaNet.Enabled = false;
                        txtMarkupNet.Enabled = false;
                        txtDescontoNet.Enabled = false;
                    }

                    if (lblStatus.Text.Equals("OR"))
                    {
                        imgStatus.ImageUrl = "~/images/Icones/OnRequest.bmp";
                    }
                    else
                    {
                        imgStatus.ImageUrl = "~/images/Icones/Confirm.bmp";
                    }

                    if (ftd.ObterPorId(Convert.ToInt32(IdFileTarifa.Text)).Flights_id == null)
                    {
                        imgFlights.ImageUrl = "~/images/Icones/flightsS.png";
                    }
                    else
                    {
                        imgFlights.ImageUrl = "~/images/Icones/flights.png";
                    }


                    if (!lblMealStatus.Text.Equals(""))
                    {
                        AtualizaMeal(Convert.ToInt32(IdFileTarifa.Text));
                    }
                    else
                    {

                        if (txtValorTarifas.Text == "0,00")
                        {
                            AtualizaMeal(Convert.ToInt32(IdFileTarifa.Text));
                        }
                        else
                        {

                            if (!Convert.ToBoolean(ftt.UpdVenda))
                            {
                                double venda = 0;

                                if (Convert.ToDecimal(txtMarkup.Text) < 1)
                                {
                                    venda = (Convert.ToDouble(txtValorTarifas.Text) / Convert.ToDouble(txtMarkup.Text));
                                }
                                else
                                {
                                    venda = (Convert.ToDouble(txtValorTarifas.Text) * Convert.ToDouble(txtMarkup.Text) / 100) + Convert.ToDouble(txtValorTarifas.Text);
                                }


                                if (!double.IsNaN(venda))
                                {
                                    ArredondaDAL arrd = new ArredondaDAL();
                                    string[] pars = Convert.ToDecimal(venda).ToString().Split(',');
                                    decimal valorArr = 0;

                                    if (pars.Count() > 1)
                                    {
                                        Arredonda arr;

                                        if (pars[1].Length == 1)
                                        {
                                            string val = pars[1] + 0;
                                            arr = arrd.ObterArr(Convert.ToInt32(val.Substring(0, 2)));
                                        }
                                        else
                                        {
                                            int val = Convert.ToInt32(pars[1].Substring(0, 2));

                                            arr = arrd.ObterArr(Convert.ToInt32(pars[1].Substring(0, 2)));
                                        }

                                        if (arr.Arredonda_recebe < 1)
                                        {
                                            valorArr = Convert.ToDecimal(pars[0]) + Convert.ToDecimal(arr.Arredonda_recebe);
                                            venda = Convert.ToDouble(valorArr);
                                        }
                                        else
                                        {
                                            valorArr = Convert.ToDecimal(pars[0]) + Convert.ToDecimal(arr.Arredonda_recebe);
                                            venda = Convert.ToDouble(valorArr);
                                        }
                                    }
                                }



                                double addDesconto = venda - (venda * Convert.ToDouble(txtDesconto.Text) / 100);

                                double addNrNoites = Convert.ToDouble(lblNumNoites.Text) * addDesconto;

                                txtVendaNet.Text = addNrNoites.ToString("N");

                                double addMarkupNet = (Convert.ToDouble(txtVendaNet.Text) * Convert.ToDouble(txtMarkupNet.Text) / 100) + Convert.ToDouble(txtVendaNet.Text);

                                double addDescontoNet = addMarkupNet - (addMarkupNet * Convert.ToDouble(txtDescontoNet.Text) / 100);

                                double multNet = Convert.ToDouble(lblPayingPax.Text) * addDescontoNet;

                                txtVenda.Text = addDescontoNet.ToString("N");

                                lblValorTotalTarifas.Text = multNet.ToString("N");

                                File_Tarifas ft = new File_Tarifas();

                                ft.File_Tarifas_id = Convert.ToInt32(IdFileTarifa.Text);
                                ft.S_merc_tarif_vendaNet = Convert.ToDecimal(addNrNoites);
                                ft.S_merc_tarif_venda = Convert.ToDecimal(addDescontoNet);
                                ft.S_merc_tarif_total = Convert.ToDecimal(multNet);
                                ft.S_merc_tarif_valor = Convert.ToDecimal(txtValorTarifas.Text);
                                ft.markup = Convert.ToDecimal(txtMarkup.Text);
                                ft.markupNet = Convert.ToDecimal(txtMarkupNet.Text);
                                ft.desconto = Convert.ToDecimal(txtDesconto.Text);
                                ft.descontoNet = Convert.ToDecimal(txtDescontoNet.Text);
                                ft.Qtd_Tarifas = Convert.ToInt32(txtQtdTarifas.Text);

                                ftd.Atualizar(ft);

                            }
                            else
                            {
                                File_Tarifas ft = new File_Tarifas();

                                txtVenda.Text = ftt.S_merc_tarif_venda.ToString();
                                txtVendaNet.Text = ftt.S_merc_tarif_vendaNet.ToString();

                                double mult = Convert.ToDouble(txtVenda.Text) * Convert.ToDouble(lblPayingPax.Text);

                                lblValorTotalTarifas.Text = mult.ToString("N2");

                                ft.File_Tarifas_id = Convert.ToInt32(IdFileTarifa.Text);
                                ft.S_merc_tarif_venda = Convert.ToDecimal(txtVenda.Text);
                                //ft.S_merc_tarif_vendaNet = Convert.ToDecimal(txtVenda.Text);
                                ft.S_merc_tarif_total = Convert.ToDecimal(mult);

                                ftd.AtualizarVendaTotal(ft);
                            }

                        }

                    }

                }


            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void AtualizaMeal(int IdFileTarifa)
        {
            try
            {
                FileTarifasDAL ftd = new FileTarifasDAL();
                File_Tarifas ft = new File_Tarifas();

                ft.File_Tarifas_id = Convert.ToInt32(IdFileTarifa);
                ft.S_merc_tarif_vendaNet = 0;
                ft.S_merc_tarif_venda = 0;
                ft.S_merc_tarif_total = 0;
                ft.S_merc_tarif_valor = 0;
                ft.markup = 0;
                ft.markupNet = 0;
                ft.desconto = 0;
                ft.descontoNet = 0;

                ftd.Atualizar(ft);
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void AtualizarStatusHoteis(object sender, CommandEventArgs e)
        {
            try
            {
                FileTarifasDAL ftd = new FileTarifasDAL();
                File_Tarifas ft = new File_Tarifas();

                string[] pars = e.CommandArgument.ToString().Split(',');

                if (pars[1].Equals("OR"))
                {
                    ft.File_Tarifas_id = Convert.ToInt32(pars[0]);
                    ft.Status = "OK";
                }
                else
                {
                    ft.File_Tarifas_id = Convert.ToInt32(pars[0]);
                    ft.Status = "OR";
                }


                ftd.AtualizarStatus(ft);
                MostrarMsg("Status alterado com sucesso.");
                PopularGridListCarrinho(Convert.ToInt32(ViewState["IdQuotGrupo"]));
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        protected void PopularGridListCarrinhoTransfers(int IdQuotGrupo)
        {
            try
            {

                FileCarrinhoDAL cd = new FileCarrinhoDAL();

                GridFileCarrinhoTransfers.DataSource = cd.MontaCarrinhoTransfers(IdQuotGrupo);
                GridFileCarrinhoTransfers.DataBind();

                //CalculaValorTotal();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void GridFileCarrinhoTranfers_DataBound(object sender, EventArgs e)
        {
            try
            {
                FileTransfersDAL ftd = new FileTransfersDAL();

                foreach (GridViewRow item in GridFileCarrinhoTransfers.Rows)
                {
                    Label lblValorTotalTarifas = (Label)item.FindControl("lblValorTotalTarifas");
                    TextBox txtQtdTarifas = (TextBox)item.FindControl("txtQtdTarifas");
                    TextBox txtValorTarifas = (TextBox)item.FindControl("txtValorTarifas");
                    TextBox txtMarkup = (TextBox)item.FindControl("txtMarkup");
                    TextBox txtMarkupNet = (TextBox)item.FindControl("txtMarkupNet");
                    TextBox txtDescontoNet = (TextBox)item.FindControl("txtDescontoNet");
                    TextBox txtDesconto = (TextBox)item.FindControl("txtDesconto");
                    TextBox txtVenda = (TextBox)item.FindControl("txtVenda");
                    TextBox txtVendaNet = (TextBox)item.FindControl("txtVendaNet");
                    Label IdFileTarifa = (Label)item.FindControl("IdFileTarifa");
                    Label lblPayingPax = (Label)item.FindControl("lblPayingPax");
                    Label lblTrfTours = (Label)item.FindControl("lblTrfTours");
                    Label lblNomeSupplier = (Label)item.FindControl("lblNomeSupplier");
                    Label lblNomeCidade = (Label)item.FindControl("lblNomeCidade");

                    Label lblNomeTrf = (Label)item.FindControl("lblNomeTrf");

                    Label lblStatus = (Label)item.FindControl("lblStatus");
                    ImageButton imgStatus = (ImageButton)item.FindControl("imgStatus");
                    ImageButton imgFlights = (ImageButton)item.FindControl("imgFlights");

                    File_Transfers ftt = ftd.ObterPorId(Convert.ToInt32(IdFileTarifa.Text));

                    CidadeDAL cidal = new CidadeDAL();

                    lblNomeCidade.Text = cidal.ObterPorNomeServico(lblNomeTrf.Text).CID_nome;

                    if (Convert.ToInt32(ViewState["PuxaMarkupStt"]) == 0)
                    {
                        txtVendaNet.Enabled = false;
                        txtMarkupNet.Enabled = false;
                        txtDescontoNet.Enabled = false;
                    }

                    if (lblStatus.Text.Equals("OR"))
                    {
                        imgStatus.ImageUrl = "~/images/Icones/OnRequest.bmp";
                    }
                    else
                    {
                        imgStatus.ImageUrl = "~/images/Icones/Confirm.bmp";
                    }

                    if (ftd.ObterPorId(Convert.ToInt32(IdFileTarifa.Text)).Flights_id == null)
                    {
                        imgFlights.ImageUrl = "~/images/Icones/flightsS.png";
                    }
                    else
                    {
                        imgFlights.ImageUrl = "~/images/Icones/flights.png";
                    }

                    if (lblTrfTours.Text.Equals("TRF"))
                    { lblNomeSupplier.ForeColor = System.Drawing.Color.Green; }
                    else
                    { lblNomeSupplier.ForeColor = System.Drawing.Color.Black; }

                    double venda = 0;

                    if (!Convert.ToBoolean(ftt.UpdVenda))
                    {
                        File_Transfers ft = new File_Transfers();

                        if (Convert.ToDecimal(txtMarkup.Text) < 1)
                        {
                            venda = (Convert.ToDouble(txtValorTarifas.Text) / Convert.ToDouble(txtMarkup.Text));
                        }
                        else
                        {
                            venda = (Convert.ToDouble(txtValorTarifas.Text) * Convert.ToDouble(txtMarkup.Text) / 100) + Convert.ToDouble(txtValorTarifas.Text);
                        }

                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        {
                            double addDesconto = venda - (venda * Convert.ToDouble(txtDesconto.Text) / 100);

                            double mult = Convert.ToDouble(lblPayingPax.Text) * addDesconto;

                            txtVendaNet.Text = addDesconto.ToString("N");

                            double addMarkupNet = (Convert.ToDouble(txtVendaNet.Text) * Convert.ToDouble(txtMarkupNet.Text) / 100) + Convert.ToDouble(txtVendaNet.Text);

                            double addDescontoNet = addMarkupNet - (addMarkupNet * Convert.ToDouble(txtDescontoNet.Text) / 100);

                            double multNet = Convert.ToDouble(lblPayingPax.Text) * addDescontoNet;

                            txtVenda.Text = addDescontoNet.ToString("N");

                            lblValorTotalTarifas.Text = multNet.ToString("N");

                            ft.File_Transf_id = Convert.ToInt32(IdFileTarifa.Text);
                            ft.Transf_vendaNet = Convert.ToDecimal(addDesconto);
                            ft.Transf_venda = Convert.ToDecimal(addDescontoNet);
                            ft.Transf_total = Convert.ToDecimal(multNet);
                            ft.markupNet = Convert.ToDecimal(txtMarkupNet.Text);
                            ft.descontoNet = Convert.ToDecimal(txtDescontoNet.Text);
                        }
                        else
                        {
                            double addDesconto = venda - (venda * Convert.ToDouble(txtDesconto.Text) / 100);

                            double mult = Convert.ToDouble(lblPayingPax.Text) * addDesconto;

                            txtVendaNet.Text = addDesconto.ToString("N");
                            txtVenda.Text = addDesconto.ToString("N");

                            lblValorTotalTarifas.Text = mult.ToString("N");

                            ft.File_Transf_id = Convert.ToInt32(IdFileTarifa.Text);
                            ft.Transf_venda = Convert.ToDecimal(addDesconto);
                            ft.Transf_vendaNet = Convert.ToDecimal(addDesconto);
                            ft.Transf_total = Convert.ToDecimal(mult);
                            ft.markupNet = 0;
                            ft.descontoNet = 0;
                        }


                        ft.Transf_valor = Convert.ToDecimal(txtValorTarifas.Text);
                        ft.markup = Convert.ToDecimal(txtMarkup.Text);
                        ft.desconto = Convert.ToDecimal(txtDesconto.Text);
                        ft.Qtd_Transf = Convert.ToInt32(txtQtdTarifas.Text);

                        ftd.Atualizar(ft);
                    }
                    else
                    {

                        File_Transfers ft = new File_Transfers();

                        txtVenda.Text = ftt.Transf_venda.ToString();
                        txtVendaNet.Text = ftt.Transf_vendaNet.ToString();

                        double mult = Convert.ToDouble(txtVenda.Text) * Convert.ToDouble(lblPayingPax.Text);

                        lblValorTotalTarifas.Text = mult.ToString("N2");

                        ft.File_Transf_id = Convert.ToInt32(IdFileTarifa.Text);
                        ft.Transf_venda = Convert.ToDecimal(txtVenda.Text);
                        //ft.Transf_vendaNet = Convert.ToDecimal(txtVenda.Text);
                        ft.Transf_total = Convert.ToDecimal(lblValorTotalTarifas.Text);

                        ftd.AtualizarVendaTotal(ft);

                    }

                }


            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void GridFileCarrinhoTransfers_RowCreated(object sender, GridViewRowEventArgs e)
        {
            try
            {
                FileTransfersDAL ftd = new FileTransfersDAL();

                foreach (GridViewRow item in GridFileCarrinhoTransfers.Rows)
                {
                    Label lblSubServico = (Label)item.FindControl("lblSubServico");
                    ImageButton imgEditSubServico = (ImageButton)item.FindControl("imgEditSubServico");

                    if (lblSubServico.Text.Equals("True"))
                    {
                        imgEditSubServico.Visible = true;
                    }
                }


            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void AtualizarStatusServicos(object sender, CommandEventArgs e)
        {
            try
            {
                FileTransfersDAL ftd = new FileTransfersDAL();
                File_Transfers ft = new File_Transfers();

                string[] pars = e.CommandArgument.ToString().Split(',');

                if (pars[1].Equals("OR"))
                {
                    ft.File_Transf_id = Convert.ToInt32(pars[0]);
                    ft.Status = "OK";
                }
                else
                {
                    ft.File_Transf_id = Convert.ToInt32(pars[0]);
                    ft.Status = "OR";
                }


                ftd.AtualizarStatus(ft);
                MostrarMsg("Status alterado com sucesso.");
                PopularGridListCarrinhoTransfers(Convert.ToInt32(ViewState["IdQuotGrupo"]));
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        protected void PopularGridListCarrinhoExtras(int IdQuotGrupo)
        {
            try
            {

                FileCarrinhoDAL cd = new FileCarrinhoDAL();

                GridFileCarrinhoExtras.DataSource = cd.MontaCarrinhoExtras(IdQuotGrupo);
                GridFileCarrinhoExtras.DataBind();

                //CalculaValorTotal();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void GridFileCarrinhoExtras_DataBound(object sender, EventArgs e)
        {
            try
            {
                FileServExtraDAL ftd = new FileServExtraDAL();

                foreach (GridViewRow item in GridFileCarrinhoExtras.Rows)
                {
                    Label lblValorTotalTarifas = (Label)item.FindControl("lblValorTotalTarifas");
                    TextBox txtQtdTarifas = (TextBox)item.FindControl("txtQtdTarifas");
                    TextBox txtValorTarifas = (TextBox)item.FindControl("txtValorTarifas");
                    TextBox txtMarkup = (TextBox)item.FindControl("txtMarkup");
                    TextBox txtMarkupNet = (TextBox)item.FindControl("txtMarkupNet");
                    TextBox txtDesconto = (TextBox)item.FindControl("txtDesconto");
                    TextBox txtDescontoNet = (TextBox)item.FindControl("txtDescontoNet");
                    TextBox txtVenda = (TextBox)item.FindControl("txtVenda");
                    TextBox txtVendaNet = (TextBox)item.FindControl("txtVendaNet");
                    Label lblPayingPax = (Label)item.FindControl("lblPayingPax");
                    Label IdFileServExtra = (Label)item.FindControl("IdFileServExtra");
                    Label lblNomeSupplier = (Label)item.FindControl("lblNomeSupplier");
                    Label lblStatus = (Label)item.FindControl("lblStatus");
                    ImageButton imgStatus = (ImageButton)item.FindControl("imgStatus");
                    ImageButton imgFlights = (ImageButton)item.FindControl("imgFlights");
                    Label lblNomeCidade = (Label)item.FindControl("lblNomeCidade");

                    File_ServExtra ftt = ftd.ObterPorId(Convert.ToInt32(IdFileServExtra.Text));

                    CidadeDAL cidal = new CidadeDAL();

                    lblNomeCidade.Text = cidal.ObterPorNomeSupplier(lblNomeSupplier.Text).CID_nome;


                    if (Convert.ToInt32(ViewState["PuxaMarkupStt"]) == 0)
                    {
                        txtVendaNet.Enabled = false;
                        txtMarkupNet.Enabled = false;
                        txtDescontoNet.Enabled = false;
                    }

                    if (lblStatus.Text.Equals("OR"))
                    {
                        imgStatus.ImageUrl = "~/images/Icones/OnRequest.bmp";
                    }
                    else
                    {
                        imgStatus.ImageUrl = "~/images/Icones/Confirm.bmp";
                    }

                    if (ftd.ObterPorId(Convert.ToInt32(IdFileServExtra.Text)).Flights_id == null)
                    {
                        imgFlights.ImageUrl = "~/images/Icones/flightsS.png";
                    }
                    else
                    {
                        imgFlights.ImageUrl = "~/images/Icones/flights.png";
                    }

                    lblNomeSupplier.ForeColor = System.Drawing.Color.Red;

                    if (!(txtValorTarifas.Text.Equals("") && txtVenda.Text.Equals("")))
                    {
                        double venda = 0;

                        if (!Convert.ToBoolean(ftt.UpdVenda))
                        {
                            if (Convert.ToDecimal(txtMarkup.Text) < 1)
                            {
                                venda = (Convert.ToDouble(txtValorTarifas.Text) / Convert.ToDouble(txtMarkup.Text));
                            }
                            else
                            {
                                venda = (Convert.ToDouble(txtValorTarifas.Text) * Convert.ToDouble(txtMarkup.Text) / 100) + Convert.ToDouble(txtValorTarifas.Text);
                            }

                            double addDesconto = venda - (venda * Convert.ToDouble(txtDesconto.Text) / 100);

                            //double mult = Convert.ToDouble(lblPayingPax.Text) * addDesconto;

                            txtVendaNet.Text = addDesconto.ToString("N");

                            double addMarkupNet = (Convert.ToDouble(txtVendaNet.Text) * Convert.ToDouble(txtMarkupNet.Text) / 100) + Convert.ToDouble(txtVendaNet.Text);

                            double addDescontoNet = addMarkupNet - (addMarkupNet * Convert.ToDouble(txtDescontoNet.Text) / 100);

                            double multNet = Convert.ToDouble(lblPayingPax.Text) * addDescontoNet;

                            txtVenda.Text = addDescontoNet.ToString("N");

                            lblValorTotalTarifas.Text = multNet.ToString("N");

                            File_ServExtra ft = new File_ServExtra();

                            ft.File_ServExtra_id = Convert.ToInt32(IdFileServExtra.Text);
                            ft.File_ServExtra_venda = Convert.ToDecimal(addDesconto);
                            ft.File_ServExtra_vendaNet = Convert.ToDecimal(addDescontoNet);
                            ft.File_ServExtra_total = Convert.ToDecimal(multNet);
                            ft.File_ServExtra_valor = Convert.ToDecimal(txtValorTarifas.Text);
                            ft.markup = Convert.ToDecimal(txtMarkup.Text);
                            ft.markupNet = Convert.ToDecimal(txtMarkupNet.Text);
                            ft.desconto = Convert.ToDecimal(txtDesconto.Text);
                            ft.descontoNet = Convert.ToDecimal(txtDescontoNet.Text);
                            ft.Qtd_ServExtr = Convert.ToInt32(txtQtdTarifas.Text);

                            ftd.Atualizar(ft);
                        }
                        else
                        {
                            File_ServExtra ft = new File_ServExtra();

                            txtVenda.Text = ftt.File_ServExtra_venda.ToString();
                            txtVendaNet.Text = ftt.File_ServExtra_vendaNet.ToString();

                            double mult = Convert.ToDouble(txtVenda.Text) * Convert.ToDouble(lblPayingPax.Text);

                            lblValorTotalTarifas.Text = mult.ToString("N2");

                            ft.File_ServExtra_id = Convert.ToInt32(IdFileServExtra.Text);
                            ft.File_ServExtra_venda = Convert.ToDecimal(txtVenda.Text);
                            ft.File_ServExtra_total = Convert.ToDecimal(lblValorTotalTarifas.Text);

                            ftd.AtualizarVendaTotal(ft);

                        }




                    }
                }


            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void AtualizarStatusServicosExtras(object sender, CommandEventArgs e)
        {
            try
            {
                FileServExtraDAL ftd = new FileServExtraDAL();
                File_ServExtra ft = new File_ServExtra();

                string[] pars = e.CommandArgument.ToString().Split(',');

                if (pars[1].Equals("OR"))
                {
                    ft.File_ServExtra_id = Convert.ToInt32(pars[0]);
                    ft.Status = "OK";
                }
                else
                {
                    ft.File_ServExtra_id = Convert.ToInt32(pars[0]);
                    ft.Status = "OR";
                }


                ftd.AtualizarStatus(ft);
                MostrarMsg("Status alterado com sucesso.");
                PopularGridListCarrinhoExtras(Convert.ToInt32(ViewState["IdQuotGrupo"]));
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        //protected void PopulaDropCidadeTransFiltro()
        //{
        //    try
        //    {
        //        CidadeDAL fl = new CidadeDAL();

        //        ddlCidadeTransFiltro.DataSource = fl.ListarTodos().OrderBy(s => s.CID_nome);
        //        ddlCidadeTransFiltro.DataValueField = "CID_id";
        //        ddlCidadeTransFiltro.DataTextField = "CID_nome";
        //        ddlCidadeTransFiltro.DataBind();

        //        ddlCidadeTransFiltro.Items.Insert(0, new ListItem("Selecione...", "0"));
        //    }
        //    catch (Exception ex)
        //    {
        //        System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
        //        Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

        //        lblMsgCadQuotatio.Text = ex.Message;
        //    }
        //}

        protected void ddlCidadeTransFiltro_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulaDropSuppliersTransPorCidade();
        }

        protected void PopulaDropSuppliersTransPorCidade()
        {
            try
            {

                SupplierDAL spd = new SupplierDAL();

                ddlSuppliersTransPorCidade.DataSource = spd.ListarTodosTrfs(Convert.ToInt32(ViewState["IdCidadeTransfer"])).OrderBy(s => s.S_nome);
                ddlSuppliersTransPorCidade.DataTextField = "S_nome";
                ddlSuppliersTransPorCidade.DataValueField = "S_id";
                ddlSuppliersTransPorCidade.DataBind();

                ddlSuppliersTransPorCidade.Items.Insert(0, new ListItem("Selecione...", "0"));

                //if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                //{
                PopularDropTransfersPorCidade();
                //}
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopularDropTransfersPorCidade()
        {

            try
            {
                MontaServicoDAL msd = new MontaServicoDAL();

                ddlTransfersPorSupplier.DataSource = msd.ListarNomeTranfersCidade(Convert.ToInt32(ViewState["IdCidadeTransfer"]), Convert.ToDateTime(txtDataFromTrans.Text), Convert.ToDateTime(txtDataToTrans.Text), Convert.ToInt32(ddlNumPaxTransfers.SelectedValue));
                ddlTransfersPorSupplier.DataValueField = "Servicos_Id";
                ddlTransfersPorSupplier.DataTextField = "Servicos_Nome";
                ddlTransfersPorSupplier.DataBind();

                ddlTransfersPorSupplier.Items.Insert(0, new ListItem("Selecione...", "0"));

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopulaDataLisTransfers()
        {
            try
            {

                MontaServicoDAL msd = new MontaServicoDAL();

                if (txtAutoTransfer.Text.Equals(""))
                {
                    DataListTransfers.DataSource = msd.ListarTodosTransfers(Convert.ToInt32(ViewState["IdCidadeTransfer"]), Convert.ToDateTime(txtDataFromTrans.Text), Convert.ToDateTime(txtDataToTrans.Text), Convert.ToInt32(ddlSuppliersTransPorCidade.SelectedValue), Convert.ToInt32(ddlNumPaxTransfers.SelectedValue), Convert.ToInt32(ddlTransfersPorSupplier.SelectedValue));
                }
                else
                {
                    DataListTransfers.DataSource = msd.ListarTodosTransfers(Convert.ToDateTime(txtDataFromTrans.Text), Convert.ToDateTime(txtDataToTrans.Text), Convert.ToInt32(ddlNumPaxTransfers.SelectedValue), txtAutoTransfer.Text, Convert.ToInt32(ViewState["IdCidadeTransfer"]));
                }

                DataListTransfers.DataBind();


            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopulaDataLisTransfersSubServicos()
        {
            try
            {

                MontaServicoDAL msd = new MontaServicoDAL();

                if (txtAutoTransfer.Text.Equals(""))
                {
                    DataListTransfersSubServicos.DataSource = msd.ListarTodosTransfersSubServico(Convert.ToInt32(ViewState["IdCidadeTransfer"]), Convert.ToDateTime(txtDataFromTrans.Text), Convert.ToDateTime(txtDataToTrans.Text), Convert.ToInt32(ddlSuppliersTransPorCidade.SelectedValue), Convert.ToInt32(ddlNumPaxTransfers.SelectedValue), Convert.ToInt32(ddlTransfersPorSupplier.SelectedValue));
                }
                else
                {
                    DataListTransfersSubServicos.DataSource = msd.ListarTodosTransfersSubServico(Convert.ToDateTime(txtDataFromTrans.Text), Convert.ToDateTime(txtDataToTrans.Text), Convert.ToInt32(ddlNumPaxTransfers.SelectedValue), txtAutoTransfer.Text, Convert.ToInt32(ViewState["IdCidadeTransfer"]));
                }

                DataListTransfersSubServicos.DataBind();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopulaDataLisToursSubServicos()
        {
            try
            {
                MontaServicoDAL msd = new MontaServicoDAL();

                if (txtAutoTour.Text.Equals(""))
                {
                    DataListToursSubServicos.DataSource = msd.ListarTodosToursSubServico(Convert.ToInt32(ViewState["IdCidadeTour"]), Convert.ToDateTime(txtDataFromTours.Text), Convert.ToDateTime(txtDataToTours.Text), Convert.ToInt32(ddlSupplierToursFiltro.SelectedValue), Convert.ToInt32(ddlNumPaxsTours.SelectedValue), Convert.ToInt32(ddlToursPorSupplier.SelectedValue));
                }
                else
                {
                    DataListToursSubServicos.DataSource = msd.ListarTodosToursSubServico(Convert.ToDateTime(txtDataFromTours.Text), Convert.ToDateTime(txtDataToTours.Text), Convert.ToInt32(ddlNumPaxsTours.SelectedValue), txtAutoTour.Text, Convert.ToInt32(ViewState["IdCidadeTour"]));
                }

                DataListToursSubServicos.DataBind();

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopularDropNumPaxsTransfers()
        {
            try
            {
                for (int i = 1; i < 51; i++)
                {
                    ListItem li = new ListItem();
                    li.Text = i.ToString();
                    li.Value = i.ToString();
                    ddlNumPaxTransfers.Items.Add(li);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopularDropNumPaxsHoteis()
        {
            try
            {
                for (int i = 1; i < 51; i++)
                {
                    ListItem li = new ListItem();
                    li.Text = i.ToString();
                    li.Value = i.ToString();
                    ddlPaxsHoteis.Items.Add(li);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopularDropEstacoesHoteis()
        {
            try
            {

                MercadoEstacaoDAL med = new MercadoEstacaoDAL();

                ddlEstacoesHoteis.DataSource = med.ObterPorSupplier(Convert.ToInt32(ddlHoteisFiltro.SelectedValue));
                ddlEstacoesHoteis.DataValueField = "S_mercado_estacao_id";
                ddlEstacoesHoteis.DataTextField = "S_mercado_estacao_nome";
                ddlEstacoesHoteis.DataBind();

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        //protected void PopulaDropCidadeToursFiltro()
        //{
        //    try
        //    {
        //        CidadeDAL fl = new CidadeDAL();

        //        dllCidadeToursFiltro.DataSource = fl.ListarTodos().OrderBy(s => s.CID_nome);
        //        dllCidadeToursFiltro.DataValueField = "CID_id";
        //        dllCidadeToursFiltro.DataTextField = "CID_nome";
        //        dllCidadeToursFiltro.DataBind();

        //        dllCidadeToursFiltro.Items.Insert(0, new ListItem("Selecione...", "0"));
        //    }
        //    catch (Exception ex)
        //    {
        //        System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
        //        Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

        //        lblMsgCadQuotatio.Text = ex.Message;
        //    }
        //}

        protected void ddlCidadeToursFiltro_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulaDropSuppliersToursPorCidade();
        }

        protected void PopulaDropSuppliersToursPorCidade()
        {
            try
            {
                SupplierDAL spd = new SupplierDAL();

                ddlSupplierToursFiltro.DataSource = spd.ListarTodosTrfs(Convert.ToInt32(ViewState["IdCidadeTour"])).OrderBy(s => s.S_nome);
                ddlSupplierToursFiltro.DataTextField = "S_nome";
                ddlSupplierToursFiltro.DataValueField = "S_id";
                ddlSupplierToursFiltro.DataBind();

                ddlSupplierToursFiltro.Items.Insert(0, new ListItem("Selecione...", "0"));


                //if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                //{
                PopularDropToursPorCidade();
                //}
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopularDropToursPorCidade()
        {

            try
            {
                MontaServicoDAL msd = new MontaServicoDAL();

                ddlToursPorSupplier.DataSource = msd.ListarNomeToursCidade(Convert.ToInt32(ViewState["IdCidadeTour"]), Convert.ToDateTime(txtDataFromTours.Text), Convert.ToDateTime(txtDataToTours.Text), Convert.ToInt32(ddlNumPaxsTours.SelectedValue));
                ddlToursPorSupplier.DataValueField = "Servicos_Id";
                ddlToursPorSupplier.DataTextField = "Servicos_Nome";
                ddlToursPorSupplier.DataBind();

                ddlToursPorSupplier.Items.Insert(0, new ListItem("Selecione...", "0"));

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopularddlTipoServExtra()
        {
            try
            {
                using (NewTierraEntities Con = new NewTierraEntities())
                {
                    ddlTipoServicoExtra.DataSource = Con.S_Servicos_Tipo.ToList();
                    ddlTipoServicoExtra.DataValueField = "Tipo_Id";
                    ddlTipoServicoExtra.DataTextField = "Tipo_Nome";
                    ddlTipoServicoExtra.DataBind();

                    ddlTipoServicoExtra.Items.Insert(0, new ListItem("Selecione", "0"));
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopulaDropSuppliersServExtra()
        {
            try
            {
                SupplierDAL spd = new SupplierDAL();

                ddlSuppliersServExtra.DataSource = spd.ListarTodos().OrderBy(s => s.S_nome);
                ddlSuppliersServExtra.DataTextField = "S_nome";
                ddlSuppliersServExtra.DataValueField = "S_id";
                ddlSuppliersServExtra.DataBind();

                ddlSuppliersServExtra.Items.Insert(0, new ListItem("Selecione", "0"));
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopularDropNumPaxsTours()
        {
            try
            {
                for (int i = 1; i < 51; i++)
                {
                    ListItem li = new ListItem();
                    li.Text = i.ToString();
                    li.Value = i.ToString();
                    ddlNumPaxsTours.Items.Add(li);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopulaDataLisTours()
        {
            try
            {

                MontaServicoDAL msd = new MontaServicoDAL();

                if (txtAutoTour.Text.Equals(""))
                {
                    DataListTours.DataSource = msd.ListarTodosTours(Convert.ToInt32(ViewState["IdCidadeTour"]), Convert.ToDateTime(txtDataFromTours.Text), Convert.ToDateTime(txtDataToTours.Text), Convert.ToInt32(ddlSupplierToursFiltro.SelectedValue), Convert.ToInt32(ddlNumPaxsTours.SelectedValue), Convert.ToInt32(ddlToursPorSupplier.SelectedValue));
                }
                else
                {
                    DataListTours.DataSource = msd.ListarTodosTours(Convert.ToDateTime(txtDataFromTours.Text), Convert.ToDateTime(txtDataToTours.Text), Convert.ToInt32(ddlNumPaxsTours.SelectedValue), txtAutoTour.Text, Convert.ToInt32(ViewState["IdCidadeTour"]));
                }

                DataListTours.DataBind();


            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopulaDropSelectFDS()
        {
            try
            {
                //PeriodosDAL pd = new PeriodosDAL();

                //ddlSelectFDS.DataSource = pd.ListarFDS(Convert.ToDateTime(txtDataPeriodoInHotel.Text),Convert.ToDateTime(txtDataPeriodoOutHotel.Text), Convert.ToInt32(ddlHoteisFiltro.SelectedValue));
                //ddlSelectFDS.DataTextField = "Texto";
                //ddlSelectFDS.DataValueField = "S_merc_periodo_id";
                //ddlSelectFDS.DataBind();

                //ddlSelectFDS.Items.Insert(0, new ListItem("Selecione...", "0"));
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void PopulaDropCategoriaHoteltarifaVazia()
        {
            try
            {
                ddlCategoriaAddTarifaHotelVazia.DataSource = new TarifCategoriaDAL().ListarTodos();
                ddlCategoriaAddTarifaHotelVazia.DataValueField = "Tarif_categoria_id";
                ddlCategoriaAddTarifaHotelVazia.DataTextField = "Tarif_categoria_nome";
                ddlCategoriaAddTarifaHotelVazia.DataBind();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void PopulaDropRoomAddTarifaHotelVazia()
        {
            try
            {
                ddlRoomAddTarifaHotelVazia.DataSource = new TipoRoomDAL().ListarTodos();
                ddlRoomAddTarifaHotelVazia.DataValueField = "Tipo_room_id";
                ddlRoomAddTarifaHotelVazia.DataTextField = "Tipo_room_nome";
                ddlRoomAddTarifaHotelVazia.DataBind();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void PopulaDropMoedaAddTafiaHotelVazia()
        {
            try
            {
                ddlMoedaAddTafiaHotelVazia.DataSource = new MoedaDAL().ListarTodos().OrderBy(m => m.Moeda_nome);
                ddlMoedaAddTafiaHotelVazia.DataTextField = "Moeda_sigla";
                ddlMoedaAddTafiaHotelVazia.DataValueField = "Moeda_id";
                ddlMoedaAddTafiaHotelVazia.DataBind();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void PopularDropClienteSelectFileCopia()
        {
            try
            {
                ClienteDAL cd = new ClienteDAL();

                ddlClienteSelectFileCopia.DataSource = cd.ListarTodos();
                ddlClienteSelectFileCopia.DataValueField = "Cliente_id";
                ddlClienteSelectFileCopia.DataTextField = "Cliente_nome";
                ddlClienteSelectFileCopia.DataBind();

                ddlClienteSelectFileCopia.Items.Insert(0, new ListItem("Selecione", "0"));

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopularDropUsuarioSelectFileCopia()
        {
            try
            {
                UsuarioDAL ud = new UsuarioDAL();

                ddlUsuarioSelectFileCopia.DataSource = ud.ListarTodos();
                ddlUsuarioSelectFileCopia.DataValueField = "US_id";
                ddlUsuarioSelectFileCopia.DataTextField = "US_nome";
                ddlUsuarioSelectFileCopia.DataBind();

                ddlUsuarioSelectFileCopia.Items.Insert(0, new ListItem("Selecione", "0"));
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PopulaCategoriaHoteis()
        {
            try
            {

                ddlCategoriaHoteis.DataSource = new CategoriaDAL().ListarTodos().OrderBy(s => s.Categ_classificacao);
                ddlCategoriaHoteis.DataValueField = "Categ_id";
                ddlCategoriaHoteis.DataTextField = "Categ_classificacao";
                ddlCategoriaHoteis.DataBind();

                ddlCategoriaHoteis.Items.Insert(0, new ListItem("Selecione...", "0"));
            }
            catch (Exception ex)
            {
                MostrarMsg("Erro. " + ex.Message);
            }
        }
        #endregion

        #region Regras

        protected bool VerificaExisteQuote()
        {
            bool rt = false;
            try
            {
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                RangeDal rd = new RangeDal();

                return rt = rd.ListarTodosOrdem(fcd.RetornaQuoteObj(txtQuoteNumber.Text).Quotation_Id).Count != 0;

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
            return rt;
        }

        protected bool VerificaExisteFile()
        {
            bool rt = false;
            try
            {
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                File_Carrinho fc = fcd.RetornaFileObj(txtQuoteNumber.Text);

                if (fc != null)
                {
                    if (fcd.VerificaExisteFile(fc.File_id))
                    { return true; }
                    else
                    { return false; }
                }

                //return rt = fcd.VerificaExisteFile(fcd.RetornaFile(txtQuoteNumber.Text));

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
            return rt;
        }

        protected int ObterIdCidadeServico(string nome)
        {
            try
            {
                return new ServicoDAL().ObterPorNome(nome).Cid_Id;
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }

            return 0;
        }

        protected void ddlAdultos_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlPaxsHoteis.SelectedValue = ddlAdultos.SelectedValue;
            ddlNumPaxTransfers.SelectedValue = ddlAdultos.SelectedValue;
            ddlNumPaxsTours.SelectedValue = ddlAdultos.SelectedValue;
        }

        protected string Limit(object Desc, int length)
        {
            StringBuilder strDesc = new StringBuilder();
            strDesc.Insert(0, Desc.ToString());

            if (strDesc.Length > length)
            {
                return strDesc.ToString().Substring(0, length);
            }
            else
            { return strDesc.ToString(); }
        }

        protected void InfoHotel(object sender, CommandEventArgs e)
        {
            int myid = Convert.ToInt32(e.CommandArgument);

            Session["Sid"] = myid;

            string script = "";
            script = script + "window.open('../PSupplier/InfoSupplier.aspx','', " + "'status=1, scrollbars=yes, width=1300, height=650, top=0, left=0');";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Infos", script, true);

        }

        protected void btnProcurarHoteis_Click(object sender, EventArgs e)
        {
            PopulaDataListHoteis();
        }

        protected void VoltarMenu(object sender, EventArgs e)
        {
            Response.Redirect("~/Pages/Index.aspx");
        }

        protected void PegaUsuario(object sender, EventArgs e)
        {
            try
            {
                UsuarioDAL d = new UsuarioDAL();

                string Senha = FormsAuthentication.HashPasswordForStoringInConfigFile
                                                        ("FRED123", "MD5");
                Usuario u = d.ObterUsuario("fredericobergson@terra.com.br", Senha);
                ddlUsuarioFiltro.SelectedValue = "0";

                //Usuario u = Session[Convert.ToString(Session["emailLogado"])] as Usuario;                
                //ddlUsuarioFiltro.SelectedValue = u.US_id.ToString();
                //ddlUsuario.SelectedValue = u.US_id.ToString();

                ddlUsuarioFiltro_SelectedIndexChanged(sender, e);
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        [WebMethod]
        protected void ddlTipoTarifa_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Convert.ToInt32(ddlTipoTarifa.SelectedValue) == 4)
            {
                statusGroup = "block";
                PopulaGridGroup();
            }
            else
            {
                statusGroup = "none";
            }

        }

        [WebMethod]
        protected void DivQuoteShow(object sender, EventArgs e)
        {
            if (divQuoteShow.Equals("none"))
            {
                divQuoteShow = "block";
                btnQuoteSelect.Visible = false;
                lblNomeClienteQuote.Visible = false;
            }
            else
            {
                divQuoteShow = "none";
                btnQuoteSelect.Visible = true;
                lblNomeClienteQuote.Visible = true;
                lblNomeClienteQuote.Text = txtNomeGrupo.Text;
                btnQuoteSelect.Text = "Quote " + txtQuoteNumber.Text;
            }
        }

        [WebMethod]
        protected void DivQuoteShowImg(object sender, ImageClickEventArgs e)
        {
            if (divQuoteShow.Equals("none"))
            {
                divQuoteShow = "block";
                btnQuoteSelect.Visible = false;
                lblNomeClienteQuote.Text = "";
            }
            else
            {
                divQuoteShow = "none";
                btnQuoteSelect.Visible = true;
                lblNomeClienteQuote.Visible = true;
                lblNomeClienteQuote.Text = txtNomeGrupo.Text;
                btnQuoteSelect.Text = "Quote " + txtQuoteNumber.Text;
            }
        }

        [WebMethod]
        protected void btnImgFilter_Click(object sender, ImageClickEventArgs e)
        {
            if (statusFiltros.Equals("none"))
            {
                statusFiltros = "block";
                txtQuoteNumber.Enabled = true;
                AutoCompleteExtenderGrupoNome.Enabled = true;
                txtNomeGrupo.Enabled = true;
            }
            else
            {
                txtNomeGrupo.Enabled = false;
                AutoCompleteExtenderGrupoNome.Enabled = false;
                txtQuoteNumber.Enabled = false;
                statusFiltros = "none";
                txtNomeGrupo.Text = "";
                txtQuoteNumber.Text = "";
            }
        }

        [WebMethod]
        public static List<string> SearchCidade(string prefixText, int count)
        {
            CidadeDAL ftd = new CidadeDAL();

            List<Cidade> cidades = new List<Cidade>();

            cidades = ftd.ListarTodos(prefixText);

            List<string> lista = new List<string>();

            foreach (Cidade p in cidades)
            {
                lista.Add(p.CID_nome);
            }

            return lista;
        }

        [WebMethod]
        public static List<string> SearchFile(string prefixText, int count)
        {
            using (NewTierraEntities Con = new NewTierraEntities())
            {
                int idUsuario = Convert.ToInt32(HttpContext.Current.Session["IDsFiltroUsuario"]);
                int idCliente = Convert.ToInt32(HttpContext.Current.Session["IDsFiltroCliente"]);

                List<Quotation> s = new List<Quotation>();

                //int lastCode = 3186;

                if (idUsuario > 0 && idCliente > 0)
                {
                    if (prefixText.Equals("*"))
                    {
                        s = (from qt in Con.Quotation_Grupo
                             join qn in Con.Quotation on qt.Quotation_Id equals qn.Quotation_Id
                             where qt.Cliente_id == idCliente &&
                                   qt.US_id == idUsuario &&
                                   qn.File_new == true
                             orderby qn.Quotation_Code
                             select qn).Distinct().ToList();

                    }
                    else
                    {
                        s = (from qt in Con.Quotation_Grupo
                             join qn in Con.Quotation on qt.Quotation_Id equals qn.Quotation_Id
                             where qn.Quotation_Code.Contains(prefixText) &&
                                   qt.Cliente_id == idCliente &&
                                   qt.US_id == idUsuario &&
                                   qn.File_new == true
                             orderby qn.Quotation_Code
                             select qn).Distinct().ToList();
                    }
                }
                else if (idUsuario > 0)
                {
                    if (prefixText.Equals("*"))
                    {
                        s = (from qt in Con.Quotation_Grupo
                             join qn in Con.Quotation on qt.Quotation_Id equals qn.Quotation_Id
                             where qt.US_id == idUsuario &&
                                   qn.File_new == true
                             orderby qn.Quotation_Code
                             select qn).Distinct().ToList();
                    }
                    else
                    {
                        s = (from qt in Con.Quotation_Grupo
                             join qn in Con.Quotation on qt.Quotation_Id equals qn.Quotation_Id
                             where qn.Quotation_Code.Contains(prefixText) &&
                                   qt.US_id == idUsuario &&
                                   qn.File_new == true
                             orderby qn.Quotation_Code
                             select qn).Distinct().ToList();
                    }
                }
                else if (idCliente > 0)
                {
                    if (prefixText.Equals("*"))
                    {
                        s = (from qt in Con.Quotation_Grupo
                             join qn in Con.Quotation on qt.Quotation_Id equals qn.Quotation_Id
                             where qt.Cliente_id == idCliente &&
                                   qn.File_new == true
                             orderby qn.Quotation_Code
                             select qn).Distinct().ToList();
                    }
                    else
                    {
                        s = (from qt in Con.Quotation_Grupo
                             join qn in Con.Quotation on qt.Quotation_Id equals qn.Quotation_Id
                             where qn.Quotation_Code.Contains(prefixText) &&
                                   qt.Cliente_id == idCliente &&
                                   qn.File_new == true
                             orderby qn.Quotation_Code
                             select qn).Distinct().ToList();
                    }
                }
                else
                {
                    if (prefixText.Equals("*"))
                    {
                        s = (from qt in Con.Quotation_Grupo
                             join qn in Con.Quotation on qt.Quotation_Id equals qn.Quotation_Id
                             where qn.File_new == true
                             orderby qn.Quotation_Code
                             select qn).Distinct().ToList();
                    }
                    else
                    {
                        s = (from qt in Con.Quotation_Grupo
                             join qn in Con.Quotation on qt.Quotation_Id equals qn.Quotation_Id
                             where qn.Quotation_Code.Contains(prefixText) &&
                                   qn.File_new == true
                             orderby qn.Quotation_Code
                             select qn).Distinct().ToList();
                    }
                }


                List<string> lista = new List<string>();

                if (s.Count == 0)
                {
                    lista.Add("Não existe file cadastrado com esses parâmetros.");

                    return lista;
                }

                foreach (Quotation p in s)
                {
                    lista.Add(p.Quotation_Code.ToString());
                }

                return lista;
            }
        }

        [WebMethod]
        public static List<string> SearchGrupo(string prefixText, int count)
        {
            using (NewTierraEntities Con = new NewTierraEntities())
            {
                int idUsuario = Convert.ToInt32(HttpContext.Current.Session["IDsFiltroUsuario"]);
                int idCliente = Convert.ToInt32(HttpContext.Current.Session["IDsFiltroCliente"]);

                List<string> s = new List<string>();

                if (idUsuario > 0 && idCliente > 0)
                {
                    if (prefixText.Equals("*"))
                    {
                        s = (from qt in Con.Quotation_Grupo
                             join qn in Con.Quotation on qt.Quotation_Id equals qn.Quotation_Id
                             where qt.Cliente_id == idCliente &&
                                   qt.US_id == idUsuario
                             orderby qn.Quotation_Code
                             select qt.Pax_Group_Name).Distinct().ToList();

                    }
                    else
                    {
                        s = (from qt in Con.Quotation_Grupo
                             join qn in Con.Quotation on qt.Quotation_Id equals qn.Quotation_Id
                             where qt.Pax_Group_Name.Contains(prefixText) &&
                                   qt.Cliente_id == idCliente &&
                                   qt.US_id == idUsuario
                             orderby qn.Quotation_Code
                             select qt.Pax_Group_Name).Distinct().ToList();
                    }
                }
                else if (idUsuario > 0)
                {
                    if (prefixText.Equals("*"))
                    {
                        s = (from qt in Con.Quotation_Grupo
                             join qn in Con.Quotation on qt.Quotation_Id equals qn.Quotation_Id
                             where qt.US_id == idUsuario
                             orderby qn.Quotation_Code
                             select qt.Pax_Group_Name).Distinct().ToList();
                    }
                    else
                    {
                        s = (from qt in Con.Quotation_Grupo
                             join qn in Con.Quotation on qt.Quotation_Id equals qn.Quotation_Id
                             where qt.Pax_Group_Name.Contains(prefixText) &&
                                   qt.US_id == idUsuario
                             orderby qn.Quotation_Code
                             select qt.Pax_Group_Name).Distinct().ToList();
                    }
                }
                else if (idCliente > 0)
                {
                    if (prefixText.Equals("*"))
                    {
                        s = (from qt in Con.Quotation_Grupo
                             join qn in Con.Quotation on qt.Quotation_Id equals qn.Quotation_Id
                             where qt.Cliente_id == idCliente
                             orderby qn.Quotation_Code
                             select qt.Pax_Group_Name).Distinct().ToList();
                    }
                    else
                    {
                        s = (from qt in Con.Quotation_Grupo
                             join qn in Con.Quotation on qt.Quotation_Id equals qn.Quotation_Id
                             where qt.Pax_Group_Name.Contains(prefixText) &&
                                   qt.Cliente_id == idCliente
                             orderby qn.Quotation_Code
                             select qt.Pax_Group_Name).Distinct().ToList();
                    }
                }
                else
                {
                    if (prefixText.Equals("*"))
                    {
                        s = (from qt in Con.Quotation_Grupo
                             join qn in Con.Quotation on qt.Quotation_Id equals qn.Quotation_Id
                             orderby qn.Quotation_Code
                             select qt.Pax_Group_Name).ToList();
                    }
                    else
                    {
                        s = (from qt in Con.Quotation_Grupo
                             join qn in Con.Quotation on qt.Quotation_Id equals qn.Quotation_Id
                             where qt.Pax_Group_Name.Contains(prefixText)
                             orderby qn.Quotation_Code
                             select qt.Pax_Group_Name).Distinct().ToList();
                    }
                }

                if (s.Count == 0)
                {
                    s.Add("Não existe file cadastrado com esses parâmetros.");

                    return s;
                }

                return s;
            }
        }

        protected void ddlUsuarioFiltro_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlUsuarioFiltro.SelectedValue.Equals("0"))
            {
                Session["IDsFiltroUsuario"] = 0;
            }
            else
            {
                Session["IDsFiltroUsuario"] = ddlUsuarioFiltro.SelectedValue;
            }
        }

        protected void ddlClienteFiltro_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlUsuarioFiltro.SelectedValue.Equals("0"))
            {
                Session["IDsFiltroCliente"] = 0;
            }
            else
            {
                Session["IDsFiltroCliente"] = ddlClienteFiltro.SelectedValue;
            }
        }

        protected void CarregarFileNumero(object sender, EventArgs e)
        {
            try
            {
                PopulaGridGroup();

                QuotationDAL qd = new QuotationDAL();

                //Quotation q = qd.ObterPorId(Convert.ToInt32(txtQuoteNumber.Text));
                Quotation q = qd.ObterPorCode(txtQuoteNumber.Text);

                QuotationGrupoDAL qgd = new QuotationGrupoDAL();

                Quotation_Grupo qg = qgd.ObterPorIdQuotation(q.Quotation_Id);

                ViewState["IdQuotGrupo"] = qg.Quotation_Grupo_Id;

                Session["SSIdQuotGrupo"] = qg.Quotation_Grupo_Id;

                PopularGridListCarrinho(qg.Quotation_Grupo_Id);
                PopularGridListCarrinhoTransfers(qg.Quotation_Grupo_Id);
                PopularGridListCarrinhoExtras(qg.Quotation_Grupo_Id);
                CalculaValorTotal();

                //PopulaNewQuote(qg.Quotation_Grupo_Id, Convert.ToInt32(ViewState["QuoteAtiva"]));

                Session["SSTotalPerPessoa"] = lblValorGrandTotalCarrinhoVenda.Text;

                Session["IdMoedaQuote"] = ddlMoeda.SelectedValue;

                //VerificaRanges(qg.Quotation_Grupo_Id);

                ViewState["IdQuote"] = q.Quotation_Id;

                if (qgd.VerificaSeries(q.Quotation_Id))
                {
                    PreencheTela(qg);
                    statusGroup = "block";
                    ddlTipoTarifa.SelectedValue = "4";
                    txtQuoteNumber.Enabled = false;
                    statusFiltros = "none";
                    btnNovoCotacao.Visible = true;
                    ddlTipoTarifa.Enabled = false;
                    btnNovoCotacao.Text = "Salvar";
                    AutoCompleteExtenderGrupoNome.Enabled = false;
                }
                else
                {
                    btnNovoCotacao.Visible = false;
                    ddlTipoTarifa.Enabled = true;
                    statusGroup = "none";
                    txtQuoteNumber.Enabled = false;
                    statusFiltros = "none";
                    AutoCompleteExtenderGrupoNome.Enabled = false;
                    PreencheTela(qg);
                }


                MarkupFileDAL mfd = new MarkupFileDAL();
                MarkupFile mf = mfd.ObterPorQGrupoFirst(qg.Quotation_Grupo_Id);

                if (mf != null)
                {
                    Session["MarkupQuote"] = mf.MarkupFile_servico;
                    Session["DescontoQuote"] = mf.MarkupFile_descontoServico;
                }
                else
                {
                    MostrarMsg("Não existe markup cadastrado para esse file, foi adicionado 0,00.");
                    Session["MarkupQuote"] = "0";
                    Session["DescontoQuote"] = "0";
                }

                PopularGridMarkup(qg.Quotation_Grupo_Id);

                //ClienteMarkupDAL climark = new ClienteMarkupDAL();
                //Session["MarkupQuote"] = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_servico);
                //Session["DescontoQuote"] = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_descontoServico);               

                Session["Quotation_Code"] = txtQuoteNumber.Text;

                ddlNumPaxsTours.SelectedValue = ddlAdultos.SelectedValue;
                ddlNumPaxTransfers.SelectedValue = ddlAdultos.SelectedValue;

                btnAtualizarCotacao.Visible = true;

                lblMsgCadQuotatio.Text = "";

                //DivQuoteShow(sender, e);

                //btnQuoteSelect.Visible = true;
                //lblNomeClienteQuote.Text = txtNomeGrupo.Text;
                //btnQuoteSelect.Text = "Quote " + txtQuoteNumber.Text;

                ViewState["QuoteAtiva"] = 1;
                //Session["QuoteAtiva"] = 1;
                lblQA.Text = "1";
                VerificaAtivo(1);

                PopulaNewQuote(qg.Quotation_Grupo_Id, Convert.ToInt32(ViewState["QuoteAtiva"]));

                if (VerificaExisteFile())
                {
                    ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "MudaCorTab('" + 2 + "')", true);
                    PopularNewFile();
                }
                else if (VerificaExisteQuote())
                {
                    ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "MudaCorTab('" + 1 + "')", true);
                }

                VerificaOpts();

                RetornaRooming();

                btnAddMarkup.Visible = true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void CarregarGrupoNome(object sender, EventArgs e)
        {
            try
            {

                QuotationDAL qd = new QuotationDAL();
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();

                Quotation_Grupo qg = qgd.ObterPorNome(txtNomeGrupo.Text);
                Quotation q = qd.ObterPorId(qg.Quotation_Id);

                txtQuoteNumber.Text = q.Quotation_Code;
                PopulaGridGroup();

                if (qgd.VerificaSeries(q.Quotation_Id))
                {
                    PreencheTela(qg);
                    statusGroup = "block";
                    ddlTipoTarifa.SelectedValue = "4";
                    txtQuoteNumber.Enabled = false;
                    statusFiltros = "block";
                    ddlTipoTarifa.Enabled = false;
                }
                else
                {
                    ddlTipoTarifa.Enabled = true;
                    statusGroup = "none";
                    txtQuoteNumber.Enabled = false;
                    statusFiltros = "block";
                    PreencheTela(qg);
                }

                ModalPopupExtenderAddTarifa.Show();

                AutoCompleteExtenderGrupoNome.Enabled = false;

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void PreencheTela(Quotation_Grupo qg)
        {
            try
            {
                txtDataIn.Text = qg.dataIN.ToShortDateString();
                txtDataOut.Text = qg.dateOut.ToShortDateString();
                lblDataNow.Text = string.Format("{0:dd MMM yyyy}", qg.dataQuote);
                txtNomeGrupo.Text = qg.Pax_Group_Name;
                ddlCliente.Text = qg.Cliente_id.ToString();
                ddlLinguagem.Text = qg.FLinguagem_id.ToString();
                ddlMoeda.Text = qg.Moeda_id.ToString();
                ddlStatus.Text = qg.Quotation_status_id.ToString();
                ddlUsuario.Text = qg.US_id.ToString();
                ddlTipoTarifa.SelectedValue = qg.S_mercado_tipo_tarifa_id.ToString();
                txtCodGrupo.Text = qg.Quotation_Grupo_Id.ToString();

                GrupoQtdAdultDAL gqa = new GrupoQtdAdultDAL();
                GrupoQtdChdDAL gqc = new GrupoQtdChdDAL();
                GrupoQtdInfDAL gqi = new GrupoQtdInfDAL();

                ddlAdultos.SelectedValue = gqa.ObterPorIdGrupo(qg.Quotation_Grupo_Id).Qtd.ToString();
                ddlChd.SelectedValue = gqc.ObterPorIdGrupo(qg.Quotation_Grupo_Id).Qtd.ToString();
                ddlInf.SelectedValue = gqi.ObterPorIdGrupo(qg.Quotation_Grupo_Id).Qtd.ToString();

                LiberaTela();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);


                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void EditarGrupo(object sender, CommandEventArgs e)
        {
            try
            {
                int myid = Convert.ToInt32(e.CommandArgument);

                QuotationGrupoDAL qgd = new QuotationGrupoDAL();

                Quotation_Grupo qg = qgd.ObterPorId(myid);

                PreencheTela(qg);
                statusFiltros = "none";

                ViewState["IdQuotGrupo"] = qg.Quotation_Grupo_Id;

                PopularGridListCarrinho(qg.Quotation_Grupo_Id);
                PopularGridListCarrinhoTransfers(qg.Quotation_Grupo_Id);
                PopularGridListCarrinhoExtras(qg.Quotation_Grupo_Id);

                ModalPopupExtenderAddTarifa.Hide();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void LimpaCampos(ControlCollection controls)
        {
            foreach (Control ctrl in controls)
            {
                if (ctrl is TextBox)
                {
                    (ctrl as TextBox).Text = string.Empty;
                }
                // ... demais controles que queira limpar

                LimpaCampos(ctrl.Controls);
            }
        }

        protected void LiberaTela()
        {
            //ddlTipoTarifa.Enabled = true;
            ddlCliente.Enabled = true;
            ddlLinguagem.Enabled = true;
            ddlMoeda.Enabled = true;
            ddlStatus.Enabled = true;
            ddlAdultos.Enabled = true;
            ddlChd.Enabled = true;
            ddlInf.Enabled = true;
            ddlUsuario.Enabled = true;
            txtDataIn.Enabled = true;
            txtDataOut.Enabled = true;
            txtNomeGrupo.Enabled = true;
            btnNovoFile.Visible = true;
        }

        protected void TravaTela()
        {
            ddlTipoTarifa.Enabled = false;
            ddlCliente.Enabled = false;
            ddlLinguagem.Enabled = false;
            ddlMoeda.Enabled = false;
            ddlStatus.Enabled = false;
            ddlAdultos.Enabled = false;
            ddlChd.Enabled = false;
            ddlInf.Enabled = false;
            ddlUsuario.Enabled = false;
            txtDataIn.Enabled = false;
            txtDataOut.Enabled = false;
            txtNomeGrupo.Enabled = false;
            btnNovoFile.Visible = false;
        }

        protected void ibtnTarifas_Command(object sender, CommandEventArgs e)
        {

            if (statusDataListHoteisTarifas.Equals("none"))
            {
                statusDataListHoteisTarifas = "block";
            }
            else
            {
                statusDataListHoteisTarifas = "none";
            }
        }

        string VerificaNulo(string texto)
        {
            if (texto == null)
            {
                return "";
            }
            else
            {
                return texto;
            }
        }

        string VerificaNuloDec(string texto)
        {
            if (texto == "")
            {
                return "0";
            }
            else
            {
                return texto;
            }
        }

        protected void lnkDataFrom_Command(object sender, CommandEventArgs e)
        {

            string[] pars = e.CommandArgument.ToString().Split('/');

            ViewState["AddDiasTipo"] = pars[0];
            ViewState["AddDiasId"] = pars[1];
            ViewState["AddDiasOrdem"] = pars[2];

            ModalPopupExtenderAddDatasCarrinho.Show();
        }

        protected void btnAddTarifaHotelVazia_Click(object sender, EventArgs e)
        {
            if (rdoOptFileHotel.SelectedValue.Equals("0"))
            {
                AddTarifaHotelVazia();
            }
            else
            {
                AddTarifaHotelVaziaFile();
            }
        }

        protected void AddTarifaHotelVazia()
        {
            try
            {
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                RangeDal rd = new RangeDal();
                FileTarifasDAL ftd = new FileTarifasDAL();

                int idFile = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                int IdQuote = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));

                File_Tarifas ft = new File_Tarifas();
                ft.Paxs = 0;
                ft.Paying_Pax = 0;
                ft.Supp_Paying_Pax = 0;
                ft.Data_From = Convert.ToDateTime(txtDataPeriodoInHotel.Text);
                ft.Data_To = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);
                ft.NumNoites = Convert.ToInt32((Convert.ToDateTime(txtDataPeriodoOutHotel.Text) - Convert.ToDateTime(txtDataPeriodoInHotel.Text)).TotalDays);
                ft.Qtd_Tarifas = 0;

                if (txtAutoHoteis.Text.Equals("")) ft.S_nome = ddlHoteisFiltro.SelectedItem.ToString(); else ft.S_nome = txtAutoHoteis.Text;

                Cidade c = new CidadeDAL().ObterPorNome(txtAutoCidadeHotel.Text);
                Supplier s = new SupplierDAL().ObterSupplierPorNome(ft.S_nome, c.CID_id);

                ft.S_email = s.S_email;
                ft.S_id = s.S_id;
                ft.Categoria = ddlCategoriaAddTarifaHotelVazia.SelectedItem.ToString();
                ft.Categoria_id = Convert.ToInt32(ddlCategoriaAddTarifaHotelVazia.SelectedValue);
                ft.Room = ddlRoomAddTarifaHotelVazia.SelectedItem.ToString();
                ft.Room_id = Convert.ToInt32(ddlRoomAddTarifaHotelVazia.SelectedValue);

                int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                ft.Ordem = Ordem;

                ft.Status = "OR";
                ft.FTC = false;
                ft.Range_id = 0;
                ft.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);
                ft.File_id = idFile;
                ft.Moeda = ddlMoedaAddTafiaHotelVazia.SelectedItem.ToString();
                ft.Moeda_id = Convert.ToInt32(ddlMoedaAddTafiaHotelVazia.SelectedValue);

                ftd.Salvar(ft);

                foreach (Ranges item in rd.ListarTodosGroupNotTC(IdQuote, Convert.ToInt32(ViewState["QuoteAtiva"])))
                {
                    Ranges r = new Ranges();

                    r.Ranges_de = item.Ranges_de;
                    r.Ranges_ate = item.Ranges_ate;
                    r.Quotation_Id = IdQuote;
                    r.Flag = "hotel";
                    r.FileTabelaId = ft.File_Tarifas_id;
                    r.markup = 0;
                    r.desconto = 0;
                    r.markupNet = 0;
                    r.descontoNet = 0;
                    r.VendaNet = 0;
                    r.Venda = 0;
                    r.ValorTotal = 0;
                    r.Valor = 0;
                    r.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);
                    r.Ordem = item.Ordem;

                    rd.Salvar(r);

                    if (rd.VerificaExisteTC(IdQuote, Convert.ToInt32(ViewState["QuoteAtiva"])))
                    {
                        Ranges rTC = new Ranges();

                        rTC.Ranges_de = "TC";
                        rTC.Ranges_ate = "TC";
                        rTC.Quotation_Id = IdQuote;
                        rTC.Flag = "hotel";
                        rTC.FileTabelaId = ft.File_Tarifas_id;
                        rTC.markup = 0;
                        rTC.desconto = 0;
                        rTC.markupNet = 0;
                        rTC.descontoNet = 0;
                        rTC.VendaNet = 0;
                        rTC.Venda = 0;
                        rTC.ValorTotal = 0;
                        rTC.Valor = 0;
                        rTC.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);
                        rTC.Ordem = item.Ordem;
                        rTC.RangeID = r.Ranges_id;
                        rTC.QtdTC = 1;

                        rd.Salvar(rTC);
                    }

                }

                PopulaNewQuote(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToInt32(ViewState["QuoteAtiva"]));
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void AddTarifaHotelVaziaFile()
        {
            try
            {
                QuoteTarifasDAL qtd = new QuoteTarifasDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                RangeDal rd = new RangeDal();

                int idFile = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                int IdQuote = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));

                Quote_Tarifas ft = new Quote_Tarifas();
                ft.Paxs = 0;
                ft.Paying_Pax = 0;
                ft.Supp_Paying_Pax = 0;
                ft.Data_From = Convert.ToDateTime(txtDataPeriodoInHotel.Text);
                ft.Data_To = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);

                ft.markup = 0;
                ft.desconto = 0;
                ft.markupNet = 0;
                ft.descontoNet = 0;
                ft.S_merc_tarif_vendaNet = 0;
                ft.S_merc_tarif_valor = 0;
                ft.S_merc_tarif_venda = 0;
                ft.S_merc_tarif_total = 0;

                ft.NumNoites = Convert.ToInt32((Convert.ToDateTime(txtDataPeriodoOutHotel.Text) - Convert.ToDateTime(txtDataPeriodoInHotel.Text)).TotalDays);
                ft.Qtd_Tarifas = 0;

                if (txtAutoHoteis.Text.Equals("")) ft.S_nome = ddlHoteisFiltro.SelectedItem.ToString(); else ft.S_nome = txtAutoHoteis.Text;

                Cidade c = new CidadeDAL().ObterPorNome(txtAutoCidadeHotel.Text);
                Supplier s = new SupplierDAL().ObterSupplierPorNome(ft.S_nome, c.CID_id);

                ft.S_email = s.S_email;
                ft.S_id = s.S_id;
                ft.Categoria = ddlCategoriaAddTarifaHotelVazia.SelectedItem.ToString();
                ft.Categoria_id = Convert.ToInt32(ddlCategoriaAddTarifaHotelVazia.SelectedValue);
                ft.Room = ddlRoomAddTarifaHotelVazia.SelectedItem.ToString();
                ft.Room_id = Convert.ToInt32(ddlRoomAddTarifaHotelVazia.SelectedValue);

                //int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;
                //ft.Ordem = Ordem;

                ft.Status = "OR";
                ft.FTC = false;
                ft.Range_id = 0;
                ft.Flag = "hotel";
                ft.TC = false;

                //ft.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                ft.File_id = idFile;
                ft.Moeda = ddlMoedaAddTafiaHotelVazia.SelectedItem.ToString();
                ft.Moeda_id = Convert.ToInt32(ddlMoedaAddTafiaHotelVazia.SelectedValue);

                qtd.Salvar(ft);

                if (qtd.VerificaExisteTC(idFile))
                {

                    Quote_Tarifas ftTC = new Quote_Tarifas();
                    ftTC.Paxs = 0;
                    ftTC.Paying_Pax = 0;
                    ftTC.Supp_Paying_Pax = 0;
                    ftTC.Data_From = Convert.ToDateTime(txtDataPeriodoInHotel.Text);
                    ftTC.Data_To = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);

                    ftTC.markup = 0;
                    ftTC.desconto = 0;
                    ftTC.markupNet = 0;
                    ftTC.descontoNet = 0;
                    ftTC.S_merc_tarif_vendaNet = 0;
                    ftTC.S_merc_tarif_valor = 0;
                    ftTC.S_merc_tarif_venda = 0;
                    ftTC.S_merc_tarif_total = 0;

                    ftTC.NumNoites = Convert.ToInt32((Convert.ToDateTime(txtDataPeriodoOutHotel.Text) - Convert.ToDateTime(txtDataPeriodoInHotel.Text)).TotalDays);
                    ftTC.Qtd_Tarifas = 0;

                    ftTC.S_nome = ft.S_nome;

                    ftTC.S_email = ft.S_email;
                    ftTC.S_id = ft.S_id;

                    ftTC.Categoria = ft.Categoria;
                    ftTC.Categoria_id = ft.Categoria_id;
                    ftTC.Room = ft.Room;
                    ftTC.Room_id = ft.Room_id;

                    ftTC.Status = "OR";
                    ftTC.FTC = false;
                    ftTC.Range_id = 0;
                    ftTC.Flag = "hotel";
                    ftTC.TC = true;

                    ftTC.File_id = idFile;
                    ftTC.Moeda = ft.Moeda;
                    ftTC.Moeda_id = ft.Moeda_id;

                    qtd.Salvar(ftTC);

                }

                PopularNewFile();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void ShowAddTarifaVazia_Click(object sender, EventArgs e)
        {
            ModalPopupExtenderAddTarifaHotelVazia.Show();
        }

        //protected void AddRange_Click(object sender, EventArgs e)
        //{

        //    try
        //    {

        //        if (!txtQuoteNumber.Text.Equals(""))
        //        {
        //            string[] pars = txtRangeAd.Text.Split(',');

        //            QuotationDAL qdal = new QuotationDAL();

        //            int IdQuote = qdal.ObterPorCode(txtQuoteNumber.Text).Quotation_Id;

        //            RangeDal rd = new RangeDal();

        //            for (int i = 0; i < pars.Count(); i++)
        //            {
        //                Ranges r = new Ranges();

        //                string[] bases = pars[i].Split('/');

        //                r.Ranges_de = Convert.ToInt32(bases[0]);
        //                r.Ranges_ate = Convert.ToInt32(bases[1]);
        //                r.Quotation_Id = IdQuote;

        //                rd.Salvar(r);

        //                TabRanges.Tabs[i].Visible = true;
        //                TabRanges.Tabs[i].HeaderText = pars[i];
        //            }

        //            TabRanges.ActiveTabIndex = 0;

        //            txtRangeAd.Text = "";

        //        }
        //        else
        //        {
        //            MostrarMsg("Selecione uma quote primeiro.");
        //            return;
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        MostrarMsg(ex.Message);
        //    }

        //}

        #endregion' 

        #region CRUD Quotation Grupo

        protected void CadastrarFile(object sender, EventArgs e)
        {
            try
            {
                QuotationDAL qd = new QuotationDAL();

                if (!txtQuoteNumber.Text.Equals(""))
                {
                    if (txtDataIn.Text.Equals("") || txtDataOut.Text.Equals(""))
                    {
                        MostrarMsg("Favor preencher todas as datas.");
                        return;
                    }

                    if (ddlTipoTarifa.SelectedValue.Equals("0") || ddlUsuario.SelectedValue.Equals("0") || ddlLinguagem.SelectedValue.Equals("0") || ddlCliente.SelectedValue.Equals("0") || ddlMoeda.SelectedValue.Equals("0") || ddlStatus.SelectedValue.Equals("0"))
                    {
                        MostrarMsg("Preencha todos os campos.");
                        return;
                    }
                }


                if (txtQuoteNumber.Text.Equals(""))
                {

                    Quotation q;

                    if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                    {
                        q = new Quotation();
                        q.Quotation_Code = DateTime.Now.ToString("ddMMM");
                        q.File_new = true;

                        qd.Salvar(q);

                        q.Quotation_Id = q.Quotation_Id;
                        q.Quotation_Code = q.Quotation_Code + q.Quotation_Id;

                        qd.Atualizar(q);
                    }
                    else
                    {
                        q = new Quotation();
                        q.Quotation_Code = "";

                        qd.Salvar(q);

                        q.Quotation_Id = q.Quotation_Id;
                        q.Quotation_Code = q.Quotation_Id.ToString();

                        qd.Atualizar(q);
                    }

                    txtQuoteNumber.Text = q.Quotation_Code.ToString();

                    LiberaTela();
                    btnNovoCotacao.Text = "Salvar";
                    txtQuoteNumber.Enabled = false;
                    ddlTipoTarifa.Enabled = true;
                    statusFiltros = "none";
                    AutoCompleteExtenderGrupoNome.Enabled = false;

                    PanelOperacoes.Visible = false;
                    btnAtualizarCotacao.Visible = false;
                    return;
                }

                Session["FileCriado"] = "File " + txtQuoteNumber.Text + " criado com sucesso.";

                Quotation_Grupo qg = new Quotation_Grupo();
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();

                qg.Pax_Group_Name = txtNomeGrupo.Text;
                qg.dataIN = Convert.ToDateTime(txtDataIn.Text);
                qg.dateOut = Convert.ToDateTime(txtDataOut.Text);
                qg.dataQuote = DateTime.Now;
                qg.Cliente_id = Convert.ToInt32(ddlCliente.SelectedValue);
                qg.S_mercado_tipo_tarifa_id = Convert.ToInt32(ddlTipoTarifa.SelectedValue);
                qg.FLinguagem_id = Convert.ToInt32(ddlLinguagem.SelectedValue);
                qg.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);
                qg.Quotation_status_id = Convert.ToInt32(ddlStatus.SelectedValue);
                qg.US_id = Convert.ToInt32(ddlUsuario.SelectedValue);

                Quotation qt = qd.ObterPorCode(txtQuoteNumber.Text);
                qg.Quotation_Id = qt.Quotation_Id;

                if (qgd.IfExists(qt.Quotation_Id))
                {
                    qg.Quotation_Grupo_NGrupo = qgd.ObterPorIdQuotationLast(qt.Quotation_Id).Quotation_Grupo_NGrupo + 1;
                }
                else
                {
                    qg.Quotation_Grupo_NGrupo = 1;
                }

                ClienteMarkupDAL climark = new ClienteMarkupDAL();
                MarkupGeralDAL markGD = new MarkupGeralDAL();

                Cliente_Markup cmk = climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue), Convert.ToDateTime(txtDataIn.Text), Convert.ToDateTime(txtDataOut.Text)).FirstOrDefault();

                List<Cliente_Markup> lstCmk = climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue), Convert.ToDateTime(txtDataIn.Text), Convert.ToDateTime(txtDataOut.Text));

                if (lstCmk.Count > 1)
                {
                    Session["FileCriado"] = Session["FileCriado"] + " - Esse cliente possui mais de um markup no mesmo período de datas.";
                }

                if (Convert.ToInt32(ddlTipoTarifa.SelectedValue) == 4)
                {
                    ddlTipoTarifa.Enabled = false;
                    btnNovoCotacao.Text = "Salvar";
                }
                else
                {
                    btnNovoCotacao.Text = "Novo";
                    PopularDrops();
                    TravaTela();
                    txtDataIn.Text = "";
                    txtDataOut.Text = "";
                    txtNomeGrupo.Text = "";
                    txtQuoteNumber.Text = "";
                }

                qgd.Salvar(qg);

                decimal markupCliente = 0, descontoCliente = 0,
                    markupServCliente = 0, descontoServCliente = 0,
                    seasonal = 0, meals = 0;

                DateTime dtInicial, dtFinal;

                if (cmk != null)
                {
                    markupCliente = Convert.ToDecimal(VerificaNuloDec(cmk.Markup_hotel.ToString()));
                    descontoCliente = Convert.ToDecimal(VerificaNuloDec(cmk.Markup_descontoHotel.ToString()));
                    markupServCliente = Convert.ToDecimal(VerificaNuloDec(cmk.Markup_servico.ToString()));
                    descontoServCliente = Convert.ToDecimal(VerificaNuloDec(cmk.Markup_descontoServico.ToString()));
                    seasonal = Convert.ToDecimal(VerificaNuloDec(cmk.Markup_seasonal.ToString()));
                    meals = Convert.ToDecimal(VerificaNuloDec(cmk.Markup_meals.ToString()));
                    dtInicial = Convert.ToDateTime(cmk.Markup_dataInicial);
                    dtFinal = Convert.ToDateTime(cmk.Markup_dataFinal);
                }
                else
                {
                    MarkupGeral mg = markGD.ObterPorAno(DateTime.Now);

                    markupCliente = Convert.ToDecimal(VerificaNuloDec(mg.MarkupGeral_hotel.ToString()));
                    descontoCliente = Convert.ToDecimal(VerificaNuloDec(mg.MarkupGeral_descontoHotel.ToString()));
                    markupServCliente = Convert.ToDecimal(VerificaNuloDec(mg.MarkupGeral_servico.ToString()));
                    descontoServCliente = Convert.ToDecimal(VerificaNuloDec(mg.MarkupGeral_descontoServico.ToString()));
                    seasonal = Convert.ToDecimal(VerificaNuloDec(mg.MarkupGeral_seasonal.ToString()));
                    meals = Convert.ToDecimal(VerificaNuloDec(mg.MarkupGeral_meals.ToString()));
                    dtInicial = Convert.ToDateTime(mg.MarkupGeral_dataInicial);
                    dtFinal = Convert.ToDateTime(mg.MarkupGeral_dataFinal);
                }


                MarkupFile mf = new MarkupFile();

                mf.MarkupFile_hotel = markupCliente;
                mf.MarkupFile_descontoHotel = descontoCliente;
                mf.MarkupFile_servico = markupServCliente;
                mf.MarkupFile_descontoServico = descontoServCliente;
                mf.MarkupFile_seasonal = seasonal;
                mf.MarkupFile_meals = meals;
                mf.MarkupFile_dataInicial = dtInicial;
                mf.MarkupFile_dataFinal = dtFinal;
                mf.Quotation_Grupo_Id = qg.Quotation_Grupo_Id;

                new MarkupFileDAL().Salvar(mf);


                Quotation_Grupo_Qtd_Adult qgqa = new Quotation_Grupo_Qtd_Adult();
                qgqa.Quotation_Grupo_Id = qg.Quotation_Grupo_Id;
                qgqa.Qtd = Convert.ToInt32(ddlAdultos.SelectedValue);
                GrupoQtdAdultDAL gqad = new GrupoQtdAdultDAL();
                gqad.Salvar(qgqa);

                ddlNumPaxsTours.SelectedValue = ddlAdultos.SelectedValue;
                ddlNumPaxTransfers.SelectedValue = ddlAdultos.SelectedValue;

                Quotation_Grupo_Qtd_Chd qgqc = new Quotation_Grupo_Qtd_Chd();
                qgqc.Quotation_Grupo_Id = qg.Quotation_Grupo_Id;
                qgqc.Qtd = Convert.ToInt32(ddlChd.SelectedValue);
                GrupoQtdChdDAL gqcd = new GrupoQtdChdDAL();
                gqcd.Salvar(qgqc);


                Quotation_Grupo_Qtd_Baby qgqb = new Quotation_Grupo_Qtd_Baby();
                qgqb.Quotation_Grupo_Id = qg.Quotation_Grupo_Id;
                qgqb.Qtd = Convert.ToInt32(ddlInf.SelectedValue);
                GrupoQtdInfDAL gqbd = new GrupoQtdInfDAL();
                gqbd.Salvar(qgqb);

                PopulaGridGroup();

                PanelOperacoes.Visible = true;

                MostrarMsg("Registro cadastrado com sucesso.");

                lblMsgCadQuotatio.Text = "";
                txtDataIn.Text = "";
                txtDataOut.Text = "";
                txtNomeGrupo.Text = "";

                btnAddMarkup.Visible = false;

                Response.Redirect("QuoteConsultaNew.aspx");
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void AtualizarFile(object sender, EventArgs e)
        {
            try
            {

                QuotationDAL qd = new QuotationDAL();
                Quotation q = new Quotation();

                if (!txtQuoteNumber.Text.Equals(""))
                {
                    if (txtDataIn.Text.Equals("") || txtDataOut.Text.Equals(""))
                    {
                        MostrarMsg("Favor preencher todas as datas.");
                        return;
                    }

                    if (ddlTipoTarifa.SelectedValue.Equals("0") || ddlUsuario.SelectedValue.Equals("0") || ddlLinguagem.SelectedValue.Equals("0") || ddlCliente.SelectedValue.Equals("0") || ddlMoeda.SelectedValue.Equals("0") || ddlStatus.SelectedValue.Equals("0"))
                    {
                        MostrarMsg("Preencha todos os campos.");
                        return;
                    }
                }

                Quotation_Grupo qg = new Quotation_Grupo();

                qg.Quotation_Grupo_Id = Convert.ToInt32(txtCodGrupo.Text);
                qg.Pax_Group_Name = txtNomeGrupo.Text;
                qg.dataIN = Convert.ToDateTime(txtDataIn.Text);
                qg.dateOut = Convert.ToDateTime(txtDataOut.Text);
                qg.dataQuote = DateTime.Now;
                qg.Cliente_id = Convert.ToInt32(ddlCliente.SelectedValue);
                qg.S_mercado_tipo_tarifa_id = Convert.ToInt32(ddlTipoTarifa.SelectedValue);
                qg.FLinguagem_id = Convert.ToInt32(ddlLinguagem.SelectedValue);
                qg.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);
                qg.Quotation_status_id = Convert.ToInt32(ddlStatus.SelectedValue);
                qg.US_id = Convert.ToInt32(ddlUsuario.SelectedValue);

                Quotation qt = qd.ObterPorCode(txtQuoteNumber.Text.Trim());
                qg.Quotation_Id = qt.Quotation_Id;

                if (Convert.ToInt32(ddlTipoTarifa.SelectedValue) == 4)
                {
                    ddlTipoTarifa.Enabled = false;
                    btnNovoCotacao.Text = "Salvar";
                }
                else
                {
                    //btnNovoCotacao.Text = "Novo";
                    //PopularDrops();
                    //TravaTela();                    
                }

                QuotationGrupoDAL qgd = new QuotationGrupoDAL();
                qgd.Atualizar(qg);

                GrupoQtdAdultDAL gqad = new GrupoQtdAdultDAL();
                Quotation_Grupo_Qtd_Adult qgqa = new Quotation_Grupo_Qtd_Adult();
                qgqa.Qtd_Adult_id = gqad.ObterPorIdGrupo(Convert.ToInt32(txtCodGrupo.Text)).Qtd_Adult_id;
                qgqa.Qtd = Convert.ToInt32(ddlAdultos.SelectedValue);
                gqad.Atualizar(qgqa);

                GrupoQtdAdultNomeDAL gqnomed = new GrupoQtdAdultNomeDAL();

                if (qgqa.Qtd > gqnomed.ListarPorAdultos(qgqa.Qtd_Adult_id).Count)
                {
                    int qtdF = qgqa.Qtd - gqnomed.ListarPorAdultos(qgqa.Qtd_Adult_id).Count;

                    for (int i = 0; i < qtdF; i++)
                    {
                        Quotation_Grupo_Qtd_Adult_Nome qnome = new Quotation_Grupo_Qtd_Adult_Nome();

                        qnome.Nome = "";
                        qnome.Qtd_Adult_id = qgqa.Qtd_Adult_id;

                        gqnomed.Salvar(qnome);
                    }
                }


                GrupoQtdChdDAL gqcd = new GrupoQtdChdDAL();
                Quotation_Grupo_Qtd_Chd qgqc = new Quotation_Grupo_Qtd_Chd();
                qgqc.Qtd_Chd_id = gqcd.ObterPorIdGrupo(Convert.ToInt32(txtCodGrupo.Text)).Qtd_Chd_id;
                qgqc.Qtd = Convert.ToInt32(ddlChd.SelectedValue);
                gqcd.Atualizar(qgqc);

                GrupoQtdChdNomeDAL gcnomed = new GrupoQtdChdNomeDAL();

                if (qgqc.Qtd > gcnomed.ListarPorChds(qgqa.Qtd_Adult_id).Count)
                {
                    int qtdF = qgqc.Qtd - gcnomed.ListarPorChds(qgqa.Qtd_Adult_id).Count;

                    for (int i = 0; i < qtdF; i++)
                    {
                        Quotation_Grupo_Qtd_Chd_Nome qnome = new Quotation_Grupo_Qtd_Chd_Nome();

                        qnome.Nome = "";
                        qnome.Qtd_Chd_id = qgqa.Qtd_Adult_id;

                        gcnomed.Salvar(qnome);
                    }
                }

                GrupoQtdInfDAL gqbd = new GrupoQtdInfDAL();
                Quotation_Grupo_Qtd_Baby qgqb = new Quotation_Grupo_Qtd_Baby();
                qgqb.Qtd_Baby_id = gqbd.ObterPorIdGrupo(Convert.ToInt32(txtCodGrupo.Text)).Qtd_Baby_id;
                qgqb.Qtd = Convert.ToInt32(ddlInf.SelectedValue);
                gqbd.Atualizar(qgqb);

                GrupoQtdInfNomeDAL ginomed = new GrupoQtdInfNomeDAL();

                if (qgqb.Qtd > ginomed.ListarPorInfs(qgqb.Qtd_Baby_id).Count)
                {
                    int qtdF = Convert.ToInt32(qgqb.Qtd - ginomed.ListarPorInfs(qgqb.Qtd_Baby_id).Count);

                    for (int i = 0; i < qtdF; i++)
                    {
                        Quotation_Grupo_Qtd_Baby_Nome qnome = new Quotation_Grupo_Qtd_Baby_Nome();

                        qnome.Nome = "";
                        qnome.Qtd_Baby_id = qgqb.Qtd_Baby_id;

                        ginomed.Salvar(qnome);
                    }
                }

                PopulaGridGroup();

                MostrarMsg("Registro atualizado com sucesso.");

                lblMsgCadQuotatio.Text = "";

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void ExcluirFile(object sender, EventArgs e)
        {
            try
            {
                QuotationDAL qd = new QuotationDAL();

                Quotation qt = qd.ObterPorCode(txtQuoteNumber.Text);

                qd.Excluir(qt);

                MostrarMsg("Registro excluído com sucesso.");

                PopularDrops();
                TravaTela();
                txtQuoteNumber.Text = "";
                txtDataIn.Text = "";
                txtDataOut.Text = "";
                txtNomeGrupo.Text = "";
                ddlAdultos.SelectedValue = "1";
                ddlChd.SelectedValue = "0";
                ddlInf.SelectedValue = "0";
                btnNovoCotacao.Visible = true;
                statusGroup = "none";
                statusFiltros = "none";

                PopularGridListCarrinho(0);
                PopularGridListCarrinhoTransfers(0);
                PopularGridListCarrinhoExtras(0);
                CalculaValorTotal();

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void NovoFile(object sender, EventArgs e)
        {
            PopularDrops();
            TravaTela();
            txtQuoteNumber.Text = "";
            txtDataIn.Text = "";
            txtDataOut.Text = "";
            txtNomeGrupo.Text = "";
            ddlAdultos.SelectedValue = "1";
            ddlChd.SelectedValue = "0";
            ddlInf.SelectedValue = "0";
            btnNovoCotacao.Visible = true;
            statusGroup = "none";
            statusFiltros = "none";
            lblDataNow.Text = string.Format("{0:dd MMM yyyy}", DateTime.Now);
            CadastrarFile(sender, e);
            btnNovoFile.Visible = false;

            PanelOperacoes.Visible = false;
            btnAtualizarCotacao.Visible = false;
        }

        protected void btnSalvarNomesPaxs_Click(object sender, EventArgs e)
        {
            try
            {

                GrupoQtdAdultDAL gqd = new GrupoQtdAdultDAL();
                GrupoQtdChdDAL gqc = new GrupoQtdChdDAL();
                GrupoQtdInfDAL gqi = new GrupoQtdInfDAL();
                GrupoQtdAdultNomeDAL gadultnome = new GrupoQtdAdultNomeDAL();
                GrupoQtdChdNomeDAL gchdnome = new GrupoQtdChdNomeDAL();
                GrupoQtdInfNomeDAL ginfnome = new GrupoQtdInfNomeDAL();
                QuotationDAL qd = new QuotationDAL();
                QuotationGrupoDAL qgrupodal = new QuotationGrupoDAL();

                Quotation qt = qd.ObterPorCode(txtQuoteNumber.Text.Trim());

                Quotation_Grupo qg = qgrupodal.ObterPorIdQuotation(qt.Quotation_Id);

                Quotation_Grupo_Qtd_Adult qa = gqd.ObterPorIdGrupo(qg.Quotation_Grupo_Id);

                foreach (DataListItem item in DataListADL.Items)
                {
                    TextBox txtADLnome = (TextBox)item.FindControl("txtADLnome");
                    Label lblIdNomeADL = (Label)item.FindControl("lblIdNomeADL");

                    Quotation_Grupo_Qtd_Adult_Nome qnome = new Quotation_Grupo_Qtd_Adult_Nome();

                    qnome.Nome = txtADLnome.Text.Trim();

                    if (lblIdNomeADL.Text.Equals(""))
                    {
                        qnome.Qtd_Adult_id = qa.Qtd_Adult_id;

                        gadultnome.Salvar(qnome);
                    }
                    else
                    {
                        qnome.Qtd_Adult_Nome_id = Convert.ToInt32(lblIdNomeADL.Text);

                        gadultnome.Atualizar(qnome);
                    }
                }

                Quotation_Grupo_Qtd_Chd qc = gqc.ObterPorIdGrupo(qg.Quotation_Grupo_Id);

                foreach (DataListItem item in DataListCHD.Items)
                {
                    TextBox txtCHDnome = (TextBox)item.FindControl("txtCHDnome");
                    Label lblIdNomeCHD = (Label)item.FindControl("lblIdNomeCHD");

                    Quotation_Grupo_Qtd_Chd_Nome qnome = new Quotation_Grupo_Qtd_Chd_Nome();

                    qnome.Nome = txtCHDnome.Text.Trim();

                    if (lblIdNomeCHD.Text.Equals(""))
                    {
                        qnome.Qtd_Chd_id = qc.Qtd_Chd_id;

                        gchdnome.Salvar(qnome);
                    }
                    else
                    {
                        qnome.Qtd_Chd_Nome_id = Convert.ToInt32(lblIdNomeCHD.Text);

                        gchdnome.Atualizar(qnome);
                    }

                }

                Quotation_Grupo_Qtd_Baby qb = gqi.ObterPorIdGrupo(qg.Quotation_Grupo_Id);

                foreach (DataListItem item in DataListINF.Items)
                {
                    TextBox txtINFnome = (TextBox)item.FindControl("txtINFnome");
                    Label lblIdNomeINF = (Label)item.FindControl("lblIdNomeINF");

                    Quotation_Grupo_Qtd_Baby_Nome qnome = new Quotation_Grupo_Qtd_Baby_Nome();

                    qnome.Nome = txtINFnome.Text.Trim();

                    if (lblIdNomeINF.Text.Equals(""))
                    {
                        qnome.Qtd_Baby_id = qb.Qtd_Baby_id;

                        ginfnome.Salvar(qnome);
                    }
                    else
                    {
                        qnome.Qtd_Baby_Nome_id = Convert.ToInt32(lblIdNomeINF.Text);

                        ginfnome.Atualizar(qnome);
                    }
                }

                MostrarMsg("Registro atualizado com sucesso.");

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnAddNomesPaxs_Click(object sender, EventArgs e)
        {
            try
            {
                GrupoQtdAdultDAL gqd = new GrupoQtdAdultDAL();
                GrupoQtdChdDAL gqc = new GrupoQtdChdDAL();
                GrupoQtdInfDAL gqi = new GrupoQtdInfDAL();
                GrupoQtdAdultNomeDAL gadultnome = new GrupoQtdAdultNomeDAL();
                GrupoQtdChdNomeDAL gchdnome = new GrupoQtdChdNomeDAL();
                GrupoQtdInfNomeDAL ginfnome = new GrupoQtdInfNomeDAL();
                QuotationGrupoDAL qgrupodal = new QuotationGrupoDAL();
                QuotationDAL qd = new QuotationDAL();

                Quotation qt = qd.ObterPorCode(txtQuoteNumber.Text.Trim());
                Quotation_Grupo qg = qgrupodal.ObterPorIdQuotation(qt.Quotation_Id);

                //Popula datalist adl
                DataListADL.DataSource = DTadl();
                DataListADL.DataBind();


                //Popula datalist chd
                DataListCHD.DataSource = DTchd();
                DataListCHD.DataBind();


                //Popula datalist inf
                DataListINF.DataSource = DTinf();
                DataListINF.DataBind();

                ModalPopupExtenderNomesPaxs.Show();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        protected DataTable DTadl()
        {
            try
            {
                GrupoQtdAdultDAL gqd = new GrupoQtdAdultDAL();
                GrupoQtdAdultNomeDAL gadultnome = new GrupoQtdAdultNomeDAL();
                QuotationGrupoDAL qgrupodal = new QuotationGrupoDAL();
                QuotationDAL qd = new QuotationDAL();

                Quotation qt = qd.ObterPorCode(txtQuoteNumber.Text.Trim());
                Quotation_Grupo qg = qgrupodal.ObterPorIdQuotation(qt.Quotation_Id);

                DataTable adl = new DataTable();
                adl.Columns.Add("Ordem");
                adl.Columns.Add("Nome");
                adl.Columns.Add("ID");

                List<Quotation_Grupo_Qtd_Adult_Nome> listaAdult = gadultnome.VerificaExiste(qg.Quotation_Grupo_Id);

                if (listaAdult.Count != 0)
                {
                    int i = 0;
                    foreach (var Adultos in listaAdult)
                    {
                        i = i + 1;

                        DataRow drw = adl.NewRow();

                        drw["Ordem"] = i;
                        drw["Nome"] = Adultos.Nome;
                        drw["ID"] = Adultos.Qtd_Adult_Nome_id;

                        adl.Rows.Add(drw);
                    }
                }
                else
                {
                    for (int i = 1; i < Convert.ToInt32(ddlAdultos.SelectedValue) + 1; i++)
                    {

                        DataRow drw = adl.NewRow();

                        drw["Ordem"] = i;
                        drw["Nome"] = "";
                        drw["ID"] = "";

                        adl.Rows.Add(drw);
                    }
                }

                return adl;

            }
            catch
            {
                throw;
            }
        }

        protected DataTable DTchd()
        {
            try
            {

                GrupoQtdChdDAL gqc = new GrupoQtdChdDAL();
                GrupoQtdChdNomeDAL gchdnome = new GrupoQtdChdNomeDAL();
                QuotationGrupoDAL qgrupodal = new QuotationGrupoDAL();
                QuotationDAL qd = new QuotationDAL();

                Quotation qt = qd.ObterPorCode(txtQuoteNumber.Text.Trim());
                Quotation_Grupo qg = qgrupodal.ObterPorIdQuotation(qt.Quotation_Id);

                DataTable chd = new DataTable();
                chd.Columns.Add("Ordem");
                chd.Columns.Add("Nome");
                chd.Columns.Add("ID");

                List<Quotation_Grupo_Qtd_Chd_Nome> listaChd = gchdnome.VerificaExiste(qg.Quotation_Grupo_Id);

                if (listaChd.Count != 0)
                {
                    int i = 0;
                    foreach (var Chds in listaChd)
                    {
                        i = i + 1;

                        DataRow drw = chd.NewRow();

                        drw["Ordem"] = i;
                        drw["Nome"] = Chds.Nome;
                        drw["ID"] = Chds.Qtd_Chd_Nome_id;

                        chd.Rows.Add(drw);
                    }
                }
                else
                {
                    for (int i = 1; i < Convert.ToInt32(ddlChd.SelectedValue) + 1; i++)
                    {

                        DataRow drw = chd.NewRow();

                        drw["Ordem"] = i;
                        drw["Nome"] = "";
                        drw["ID"] = "";

                        chd.Rows.Add(drw);
                    }
                }

                return chd;

            }
            catch
            {
                throw;
            }
        }

        protected DataTable DTinf()
        {
            try
            {
                GrupoQtdInfDAL gqi = new GrupoQtdInfDAL();
                GrupoQtdInfNomeDAL ginfnome = new GrupoQtdInfNomeDAL();
                QuotationGrupoDAL qgrupodal = new QuotationGrupoDAL();
                QuotationDAL qd = new QuotationDAL();

                Quotation qt = qd.ObterPorCode(txtQuoteNumber.Text.Trim());
                Quotation_Grupo qg = qgrupodal.ObterPorIdQuotation(qt.Quotation_Id);

                DataTable inf = new DataTable();
                inf.Columns.Add("Ordem");
                inf.Columns.Add("Nome");
                inf.Columns.Add("ID");

                List<Quotation_Grupo_Qtd_Baby_Nome> listaInf = ginfnome.VerificaExiste(qg.Quotation_Grupo_Id);

                if (listaInf.Count != 0)
                {
                    int i = 0;
                    foreach (var Infs in listaInf)
                    {
                        i = i + 1;

                        DataRow drw = inf.NewRow();

                        drw["Ordem"] = i;
                        drw["Nome"] = Infs.Nome;
                        drw["ID"] = Infs.Qtd_Baby_Nome_id;

                        inf.Rows.Add(drw);
                    }
                }
                else
                {

                    for (int i = 1; i < Convert.ToInt32(ddlInf.SelectedValue) + 1; i++)
                    {

                        DataRow drw = inf.NewRow();

                        drw["Ordem"] = i;

                        inf.Rows.Add(drw);
                    }
                }

                return inf;
            }
            catch
            {
                throw;
            }
        }

        protected void deleteAdl_Command(object sender, CommandEventArgs e)
        {
            try
            {

                int IdNome = Convert.ToInt32(e.CommandArgument);

                GrupoQtdAdultNomeDAL gd = new GrupoQtdAdultNomeDAL();

                int IdQtdAdult = gd.ObterPorId(IdNome).Qtd_Adult_id;

                gd.Excluir(gd.ObterPorId(IdNome));

                GrupoQtdAdultDAL gqd = new GrupoQtdAdultDAL();

                Quotation_Grupo_Qtd_Adult qgrupoadl = gqd.ObterPorId(IdQtdAdult);

                int qtdAdultos = Convert.ToInt32(qgrupoadl.Qtd) - 1;

                Quotation_Grupo_Qtd_Adult adult = new Quotation_Grupo_Qtd_Adult();

                adult.Qtd = qtdAdultos;
                adult.Qtd_Adult_id = qgrupoadl.Qtd_Adult_id;

                gqd.Atualizar(adult);

                for (int i = DTadl().Rows.Count - 1; i >= 0; i--)
                {
                    DataRow dr = DTadl().Rows[i];
                    if (dr["ID"].ToString().Equals(IdNome.ToString()))
                        dr.Delete();
                }

                ddlAdultos.SelectedValue = DTadl().Rows.Count.ToString();

                DataListADL.DataSource = DTadl();
                DataListADL.DataBind();

                MostrarMsg("Registro excluído com sucesso.");
                ModalPopupExtenderNomesPaxs.Show();

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        protected void deleteChd_Command(object sender, CommandEventArgs e)
        {
            try
            {

                int IdNome = Convert.ToInt32(e.CommandArgument);

                GrupoQtdChdNomeDAL gd = new GrupoQtdChdNomeDAL();

                int IdQtdChd = Convert.ToInt32(gd.ObterPorId(IdNome).Qtd_Chd_id);

                gd.Atualizar(gd.ObterPorId(IdNome));

                GrupoQtdChdDAL gqd = new GrupoQtdChdDAL();

                Quotation_Grupo_Qtd_Chd qgrupochd = gqd.ObterPorId(IdQtdChd);

                int qtdChd = Convert.ToInt32(qgrupochd.Qtd) - 1;

                Quotation_Grupo_Qtd_Chd chd = new Quotation_Grupo_Qtd_Chd();

                chd.Qtd = qtdChd;
                chd.Qtd_Chd_id = qgrupochd.Qtd_Chd_id;

                gqd.Atualizar(chd);

                for (int i = DTchd().Rows.Count - 1; i >= 0; i--)
                {
                    DataRow dr = DTchd().Rows[i];
                    if (dr["ID"].ToString().Equals(IdNome.ToString()))
                        dr.Delete();
                }

                ddlChd.SelectedValue = DTchd().Rows.Count.ToString();

                DataListCHD.DataSource = DTchd();
                DataListCHD.DataBind();

                MostrarMsg("Registro excluído com sucesso.");
                ModalPopupExtenderNomesPaxs.Show();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        protected void deleteInf_Command(object sender, CommandEventArgs e)
        {
            try
            {

                int IdNome = Convert.ToInt32(e.CommandArgument);

                GrupoQtdInfNomeDAL gd = new GrupoQtdInfNomeDAL();

                int IdQtdInf = Convert.ToInt32(gd.ObterPorId(IdNome).Qtd_Baby_id);

                gd.Excluir(gd.ObterPorId(IdNome));

                GrupoQtdInfDAL gqd = new GrupoQtdInfDAL();

                Quotation_Grupo_Qtd_Baby qgrupoinf = gqd.ObterPorId(IdQtdInf);

                int qtdInf = Convert.ToInt32(qgrupoinf.Qtd) - 1;

                Quotation_Grupo_Qtd_Baby inf = new Quotation_Grupo_Qtd_Baby();

                inf.Qtd = qtdInf;
                inf.Qtd_Baby_id = qgrupoinf.Qtd_Baby_id;

                gqd.Atualizar(inf);

                for (int i = DTinf().Rows.Count - 1; i >= 0; i--)
                {
                    DataRow dr = DTinf().Rows[i];
                    if (dr["ID"].ToString().Equals(IdNome.ToString()))
                        dr.Delete();
                }

                ddlInf.SelectedValue = DTinf().Rows.Count.ToString();

                DataListINF.DataSource = DTchd();
                DataListINF.DataBind();

                MostrarMsg("Registro excluído com sucesso.");
                ModalPopupExtenderNomesPaxs.Show();

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        #endregion

        #region Files Hoteis Carrinho

        protected void BtnAddMeal(object sender, CommandEventArgs e)
        {
            if (rdoOptFileHotel.SelectedValue.Equals("0"))
            {
                btnAddRoomsMealByBases(Convert.ToInt32(e.CommandArgument));
            }
            else
            {
                btnAddRoomsMealByBasesDirFile(Convert.ToInt32(e.CommandArgument));
            }
            //btnAddMeals_Command(sender,  e);
        }

        protected void btnAddMeals_Command(object sender, CommandEventArgs e)
        {
            try
            {

                FileTarifasDAL ftd = new FileTarifasDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                ClienteDAL cli = new ClienteDAL();

                ClienteMarkupDAL climark = new ClienteMarkupDAL();

                DateTime In = Convert.ToDateTime(txtDataPeriodoInHotel.Text);
                DateTime Out = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);

                //double NumNoites = (Out - In).TotalDays;
                double NumNoites = 0;

                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), In);

                decimal markupcliente = 0, descontocliente = 0;
                if (mkfile != null)
                {
                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                    descontocliente = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                }
                else
                {
                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(In);

                    if (mgfile != null)
                    {
                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                        descontocliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                    }
                    else
                    {
                        MostrarMsg("Não existe Markup cadastrado.");
                        return;
                    }
                }

                //decimal markupcliente = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_hotel);
                //decimal descontocliente = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_descontoHotel);

                if (fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])) == null)
                {
                    File_Carrinho fc = new File_Carrinho();

                    fc.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                    fcd.Salvar(fc);
                }


                DateTime dataPeriodo = Convert.ToDateTime(txtDataPeriodoInHotel.Text);
                int iCount = 0;
                int Cfds = 0;

                foreach (DataListItem item in DataListHoteis.Items)
                {
                    DataList DataListHoteisMeals = (DataList)item.FindControl("DataListHoteisMeals");

                    Label lblTituloPacote = (Label)item.FindControl("lblTituloPacote");
                    Label lblFDS = (Label)item.FindControl("lblFDS");
                    Label lblNomePacote = (Label)item.FindControl("lblNomePacote");

                    string[] FDSs = lblFDS.Text.ToString().Split('/');

                    DayOfWeek DayIn = ReturnDayPT(FDSs[0].Trim());
                    DayOfWeek DayOut = ReturnDayPT(FDSs[1].Trim());

                    foreach (DataListItem item2 in DataListHoteisMeals.Items)
                    {
                        Label lblMoedaMeal = (Label)item2.FindControl("lblMoedaMeal");
                        Label lblMoedaId = (Label)item2.FindControl("lblMoedaId");
                        Label lblValorTotalMeal = (Label)item2.FindControl("lblValorTotalMeal");
                        Label lblMealId = (Label)item2.FindControl("lblMealId");
                        Label lblMealNome = (Label)item2.FindControl("lblMealNome");
                        Label lblStatusMeal = (Label)item2.FindControl("lblStatusMeal");
                        Label lblSupplierMealId = (Label)item2.FindControl("lblSupplierMealId");

                        Cfds = 0;

                        bool jaAdd = ftd.VerificaMeal(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"])), Convert.ToInt32(lblMealId.Text));

                        if (Convert.ToInt32(lblMealId.Text) == Convert.ToInt32(e.CommandArgument) && !jaAdd)
                        {

                            //btnAddRoomsMealByBases(Convert.ToInt32(e.CommandArgument));

                            File_Tarifas ft = new File_Tarifas();
                            MoedaDAL mod = new MoedaDAL();
                            CambioDAL cambDal = new CambioDAL();
                            MealDAL md = new MealDAL();

                            S_Mercado_Meal smercmeal = md.ObterPorId(Convert.ToInt32(lblMealId.Text));

                            decimal valorComCambio;
                            decimal valor = 0;

                            if (!lblStatusMeal.Text.Equals(""))
                            {
                                ft.S_meal_status = lblStatusMeal.Text;
                            }
                            else
                            {
                                if (lblMoedaId.Text != ddlMoeda.SelectedValue)
                                {
                                    Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(lblMoedaId.Text), Convert.ToInt32(ddlMoeda.SelectedValue));

                                    valor = Convert.ToDecimal(lblValorTotalMeal.Text);
                                    valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                                    ft.S_merc_tarif_valor = valorComCambio;
                                }
                                else
                                {
                                    ft.S_merc_tarif_valor = Convert.ToDecimal(lblValorTotalMeal.Text);
                                }
                            }

                            int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                            ft.Ordem = Ordem;

                            ft.Paxs = Convert.ToInt32(ddlAdultos.SelectedValue);
                            ft.Paying_Pax = Convert.ToInt32(ddlAdultos.SelectedValue);
                            ft.Supp_Paying_Pax = Convert.ToInt32(ddlAdultos.SelectedValue);
                            ft.Qtd_Tarifas = Convert.ToInt32(ddlAdultos.SelectedValue);

                            ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                            ft.S_meal_nome = lblMealNome.Text;
                            ft.S_meal_id = Convert.ToInt32(lblMealId.Text);
                            ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;

                            SupplierDAL sd = new SupplierDAL();
                            MarkupPaisDAL mkd = new MarkupPaisDAL();

                            Supplier spp = sd.ObterPorId(Convert.ToInt32(lblSupplierMealId.Text));

                            if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                            {
                                MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                                if (lblStatusMeal.Text.Equals(""))
                                {
                                    ft.markup = mkp.Markup;
                                    ft.desconto = mkp.Desconto;
                                    ft.markupNet = markupcliente;
                                    ft.descontoNet = descontocliente;
                                }
                                else
                                {
                                    ft.markup = 0;
                                    ft.desconto = 0;
                                    ft.markupNet = 0;
                                    ft.descontoNet = 0;
                                }
                            }
                            else
                            {
                                if (lblStatusMeal.Text.Equals(""))
                                {
                                    ft.markup = markupcliente;
                                    ft.desconto = descontocliente;
                                    ft.markupNet = 0;
                                    ft.descontoNet = 0;
                                }
                                else
                                {
                                    ft.markup = 0;
                                    ft.desconto = 0;
                                    ft.markupNet = 0;
                                    ft.descontoNet = 0;
                                }
                            }


                            ft.Data_From = Convert.ToDateTime(txtDataPeriodoInHotel.Text);
                            ft.Data_To = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);

                            NumNoites = (Convert.ToDateTime(ft.Data_To) - Convert.ToDateTime(ft.Data_From)).TotalDays;

                            if (NumNoites == 0.0)
                            {
                                NumNoites = 1;
                            }

                            ft.S_id = Convert.ToInt32(lblSupplierMealId.Text);
                            ft.S_nome = lblTituloPacote.Text;
                            ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);
                            ft.S_email = spp.S_email;
                            ft.Meal = true;
                            ft.Status = "OR";

                            ft.NumNoites = Convert.ToInt32(NumNoites);
                            ft.FTC = false;

                            ftd.Salvar(ft);
                        }





                    }

                }

                PopularGridListCarrinho(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                CalculaValorTotal();
                MostrarMsg("Tarifas adicionadas ao file com sucesso.");

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void BtnAddRooms(object sender, EventArgs e)
        {
            if (rdoOptFileHotel.SelectedValue.Equals("0"))
            {
                btnAddRoomsByBases();
            }
            else
            {
                btnAddRoomsByBasesDirFile();
            }
            //btnAddRooms_Click(sender, e);
        }

        protected void btnAddRooms_Click(object sender, EventArgs e)
        {
            try
            {
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                ClienteDAL cli = new ClienteDAL();

                ClienteMarkupDAL climark = new ClienteMarkupDAL();

                DateTime In = Convert.ToDateTime(txtDataPeriodoInHotel.Text);
                DateTime Out = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);

                //double NumNoites = (Out - In).TotalDays;
                double NumNoites = 0;

                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), In);
                decimal markupcliente = 0, descontocliente = 0;
                if (mkfile != null)
                {
                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                    descontocliente = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                }
                else
                {
                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(In);

                    if (mgfile != null)
                    {
                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                        descontocliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                    }
                    else
                    {
                        MostrarMsg("Não existe Markup cadastrado.");
                        return;
                    }
                }

                //decimal markupcliente = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_hotel);
                //decimal descontocliente = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_descontoHotel);

                if (fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])) == null)
                {
                    File_Carrinho fc = new File_Carrinho();

                    fc.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                    fcd.Salvar(fc);
                }

                DateTime dataPeriodo = Convert.ToDateTime(txtDataPeriodoInHotel.Text);
                DateTime dataPeriodoout = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);
                int iCount = 0;
                int Cfds = 0;

                ViewState["verify"] = In;

                foreach (DataListItem item in DataListHoteis.Items)
                {
                    DataList DataListHoteisTarifas = (DataList)item.FindControl("DataListHoteisTarifas");

                    Label lblTituloPacote = (Label)item.FindControl("lblTituloPacote");
                    Label lblFDS = (Label)item.FindControl("lblFDS");
                    Label lblNomePacote = (Label)item.FindControl("lblNomePacote");

                    string[] FDSs = lblFDS.Text.ToString().Split('/');

                    DayOfWeek DayIn = ReturnDayPT(FDSs[0].Trim());
                    DayOfWeek DayOut = ReturnDayPT(FDSs[1].Trim());

                    foreach (DataListItem item2 in DataListHoteisTarifas.Items)
                    {
                        Label lblIdTarifa = (Label)item2.FindControl("lblIdTarifa");
                        DropDownList ddlQtd = (DropDownList)item2.FindControl("ddlQtd");
                        Label lblValorTotal = (Label)item2.FindControl("lblValorTotal");
                        Label lblRoom = (Label)item2.FindControl("lblRoom");
                        Label lblMoeda = (Label)item2.FindControl("lblMoeda");
                        Label lblCategoria = (Label)item2.FindControl("lblCategoria");
                        Label lblCategoriaId = (Label)item2.FindControl("lblCategoriaId");
                        Label lblRoomId = (Label)item2.FindControl("lblRoomId");
                        Label lblSupplierId = (Label)item2.FindControl("lblSupplierId");
                        Label lblEmailSupplier = (Label)item2.FindControl("lblEmailSupplier");
                        Label lblMoedaId = (Label)item2.FindControl("lblMoedaId");


                        if (ddlQtd.SelectedValue != "0")
                        {
                            ViewState["CategoriaVer"] = lblCategoria.Text.Trim();
                            ViewState["RoomVer"] = lblRoom.Text.Trim();
                            ViewState["ValorTotalRoom"] = lblValorTotal.Text.Trim();
                            ViewState["QtdSelectValue"] = ddlQtd.SelectedValue;
                        }


                        if (ddlQtd.SelectedValue != "0")
                        {
                            ViewState["Paying"] = ddlQtd.SelectedValue;

                            if (!FDSs[0].Trim().Equals(""))
                            {
                                Cfds = 1;

                                if (IsBetween(DayIn, DayOut, dataPeriodo.DayOfWeek) && IsBetween(DayIn, DayOut, dataPeriodoout.DayOfWeek))
                                {
                                    //------começo

                                    AdicionaDtPrimeira(markupcliente, descontocliente, dataPeriodo);

                                    //------fim

                                } // if between
                                else
                                {
                                    AdicionaQtoDiff(markupcliente, descontocliente, dataPeriodo);
                                    break;
                                }


                            }
                            else
                            {

                                //btnAddRoomsByBases();

                                Cfds = 0;

                                File_Tarifas ft = new File_Tarifas();
                                TipoRoomDAL trd = new TipoRoomDAL();
                                MoedaDAL mod = new MoedaDAL();
                                CambioDAL cambDal = new CambioDAL();
                                MealDAL mdd = new MealDAL();
                                PeriodosDAL pdao = new PeriodosDAL();

                                MercadoTarifaDAL mtdal = new MercadoTarifaDAL();

                                S_Mercado_Tarifa smerctariff = mtdal.ObterPorId(Convert.ToInt32(lblIdTarifa.Text));

                                List<S_Mercado_Meal> listameals = mdd.ListarAddFile(smerctariff.S_merc_periodo_id);

                                S_Mercado_Periodo smper = pdao.ObterPorIdPeriodo(smerctariff.S_merc_periodo_id);


                                if (smper.MinimoNoites_id != null)
                                {
                                    double noites = (Out - In).TotalDays;

                                    if (Convert.ToInt32(noites) < smper.MinimoNoites.MinimoNoites_qtd)
                                    {
                                        MostrarMsg("O mínimo de noites desse pacote é " + smper.MinimoNoites.MinimoNoites_qtd);
                                        return;
                                    }

                                }

                                ft.FdsFrom = smper.S_merc_periodo_fdsFrom;
                                ft.FdsTo = smper.S_merc_periodo_fdsTo;

                                decimal valorComCambio;
                                decimal valor = 0;

                                if (lblValorTotal.Text.Equals(""))
                                {

                                    ft.S_merc_tarif_valor = 0;

                                }
                                else
                                {
                                    if (lblMoedaId.Text != ddlMoeda.SelectedValue)
                                    {
                                        Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(lblMoedaId.Text), Convert.ToInt32(ddlMoeda.SelectedValue));

                                        valor = Convert.ToDecimal(lblValorTotal.Text);
                                        valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                                        //if (smerctariff.S_merc_tarif_porApartamento == true)
                                        //{
                                        //    valor = Convert.ToDecimal(lblValorTotal.Text) / Convert.ToDecimal(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                                        //    valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);
                                        //}
                                        //else
                                        //{
                                        //    valor = Convert.ToDecimal(lblValorTotal.Text);
                                        //    valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);
                                        //}


                                        ft.S_merc_tarif_valor = valorComCambio;
                                    }
                                    else
                                    {
                                        //if (smerctariff.S_merc_tarif_porApartamento == true)
                                        //{
                                        //    valor = Convert.ToDecimal(lblValorTotal.Text) / Convert.ToDecimal(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                                        //    ft.S_merc_tarif_valor = valor;
                                        //}
                                        //else
                                        //{
                                        //    ft.S_merc_tarif_valor = Convert.ToDecimal(lblValorTotal.Text);
                                        //}

                                        ft.S_merc_tarif_valor = Convert.ToDecimal(lblValorTotal.Text);
                                    }
                                }

                                int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                                ft.Ordem = Ordem;

                                ft.Paxs = Convert.ToInt32(ddlQtd.SelectedValue) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                                ft.Paying_Pax = Convert.ToInt32(ddlQtd.SelectedValue) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                                ft.Supp_Paying_Pax = Convert.ToInt32(ddlQtd.SelectedValue) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                                ft.Qtd_Tarifas = Convert.ToInt32(ddlQtd.SelectedValue) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);


                                ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                                ft.S_nome = lblTituloPacote.Text;
                                ft.Categoria = lblCategoria.Text;
                                ft.Room = lblRoom.Text;
                                ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;

                                if (!lblNomePacote.Text.Equals(""))
                                {
                                    ft.NomePacote = lblNomePacote.Text.Trim();
                                }
                                else
                                {
                                    ft.NomePacote = null;
                                }



                                if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                                {
                                    SupplierDAL sd = new SupplierDAL();
                                    MarkupPaisDAL mkd = new MarkupPaisDAL();

                                    Supplier spp = sd.ObterPorId(Convert.ToInt32(lblSupplierId.Text));
                                    MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                                    ft.markup = mkp.Markup;
                                    ft.desconto = mkp.Desconto;
                                    ft.markupNet = markupcliente;
                                    ft.descontoNet = descontocliente;
                                }
                                else
                                {
                                    ft.markup = markupcliente;
                                    ft.desconto = descontocliente;
                                    ft.markupNet = 0;
                                    ft.descontoNet = 0;
                                }


                                ft.Data_From = Convert.ToDateTime(txtDataPeriodoInHotel.Text);
                                ft.Data_To = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);

                                NumNoites = (Convert.ToDateTime(ft.Data_To) - Convert.ToDateTime(ft.Data_From)).TotalDays;

                                if (NumNoites == 0.0)
                                {
                                    NumNoites = 1;
                                }

                                ft.Categoria_id = Convert.ToInt32(lblCategoriaId.Text);
                                ft.Room_id = Convert.ToInt32(lblRoomId.Text);
                                ft.S_id = Convert.ToInt32(lblSupplierId.Text);
                                ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);
                                ft.S_email = lblEmailSupplier.Text;
                                ft.Status = "OR";
                                ft.NumNoites = Convert.ToInt32(NumNoites);
                                ft.FTC = false;

                                if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("N"))
                                {
                                    DescricaoDAL dd = new DescricaoDAL();

                                    string remark;

                                    if (dd.ObterPorIdSupp(Convert.ToInt32(lblSupplierId.Text)) != null)
                                    {
                                        remark = dd.ObterPorIdSupp(Convert.ToInt32(lblSupplierId.Text)).Desc_remarks;
                                    }
                                    else
                                    {
                                        remark = "No remarks";
                                    }

                                    lblMsgOperador.Text = remark;
                                    ModalPopupExtenderMsgOperador.Show();
                                }

                                ftd.Salvar(ft);

                                ddlQtd.SelectedValue = "0";
                            }


                        }


                    }


                }

                if (Cfds == 1)
                {
                    dataPeriodo = dataPeriodo.AddDays(Convert.ToInt32(ViewState["Count"]));

                    if (dataPeriodo != Convert.ToDateTime(txtDataPeriodoOutHotel.Text))
                    {
                        AdicionaQtoVerif(markupcliente, descontocliente, dataPeriodo);
                    }
                }

                PopularGridListCarrinho(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                CalculaValorTotal();
                MostrarMsg("Tarifas adicionadas ao file com sucesso.");

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        protected void AdicionaDtPrimeira(decimal markupcliente, decimal descontocliente, DateTime dataPeriodo)
        {
            try
            {

                FileTarifasDAL ftd = new FileTarifasDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                DateTime dataPeriodoout = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);

                foreach (DataListItem item in DataListHoteis.Items)
                {
                    DataList DataListHoteisTarifas = (DataList)item.FindControl("DataListHoteisTarifas");

                    Label lblTituloPacote = (Label)item.FindControl("lblTituloPacote");
                    Label lblFDS = (Label)item.FindControl("lblFDS");
                    Label lblNomePacote = (Label)item.FindControl("lblNomePacote");

                    string[] FDSs = lblFDS.Text.ToString().Split('/');

                    DayOfWeek DayIn = ReturnDayPT(FDSs[0].Trim());
                    DayOfWeek DayOut = ReturnDayPT(FDSs[1].Trim());


                    foreach (DataListItem item2 in DataListHoteisTarifas.Items)
                    {
                        Label lblIdTarifa = (Label)item2.FindControl("lblIdTarifa");
                        DropDownList ddlQtd = (DropDownList)item2.FindControl("ddlQtd");
                        Label lblValorTotal = (Label)item2.FindControl("lblValorTotal");
                        Label lblRoom = (Label)item2.FindControl("lblRoom");
                        Label lblMoeda = (Label)item2.FindControl("lblMoeda");
                        Label lblCategoria = (Label)item2.FindControl("lblCategoria");
                        Label lblCategoriaId = (Label)item2.FindControl("lblCategoriaId");
                        Label lblRoomId = (Label)item2.FindControl("lblRoomId");
                        Label lblSupplierId = (Label)item2.FindControl("lblSupplierId");
                        Label lblEmailSupplier = (Label)item2.FindControl("lblEmailSupplier");
                        Label lblMoedaId = (Label)item2.FindControl("lblMoedaId");

                        if (lblCategoria.Text.Equals(ViewState["CategoriaVer"]) && lblRoom.Text.Equals(ViewState["RoomVer"]) && IsBetween(DayIn, DayOut, dataPeriodo.DayOfWeek) && IsBetween(DayIn, DayOut, dataPeriodoout.DayOfWeek))
                        {

                            File_Tarifas ft = new File_Tarifas();
                            TipoRoomDAL trd = new TipoRoomDAL();
                            MoedaDAL mod = new MoedaDAL();
                            CambioDAL cambDal = new CambioDAL();
                            PeriodosDAL pdao = new PeriodosDAL();

                            MercadoTarifaDAL mtdal = new MercadoTarifaDAL();

                            S_Mercado_Tarifa smerctariff = mtdal.ObterPorId(Convert.ToInt32(lblIdTarifa.Text));

                            S_Mercado_Periodo smper = pdao.ObterPorIdPeriodo(smerctariff.S_merc_periodo_id);

                            ft.FdsFrom = smper.S_merc_periodo_fdsFrom;
                            ft.FdsTo = smper.S_merc_periodo_fdsTo;

                            decimal valorComCambio;
                            decimal valor = 0;

                            if (lblMoedaId.Text != ddlMoeda.SelectedValue)
                            {
                                Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(lblMoedaId.Text), Convert.ToInt32(ddlMoeda.SelectedValue));

                                valor = Convert.ToDecimal(lblValorTotal.Text);
                                valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                                //if (smerctariff.S_merc_tarif_porApartamento == true)
                                //{
                                //    valor = Convert.ToDecimal(lblValorTotal.Text) / Convert.ToDecimal(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                                //    valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);
                                //}
                                //else
                                //{
                                //    valor = Convert.ToDecimal(lblValorTotal.Text);
                                //    valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);
                                //}


                                ft.S_merc_tarif_valor = valorComCambio;
                            }
                            else
                            {
                                //if (smerctariff.S_merc_tarif_porApartamento == true)
                                //{
                                //    valor = Convert.ToDecimal(lblValorTotal.Text) / Convert.ToDecimal(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                                //    ft.S_merc_tarif_valor = valor;
                                //}
                                //else
                                //{
                                //    ft.S_merc_tarif_valor = Convert.ToDecimal(lblValorTotal.Text);
                                //}

                                ft.S_merc_tarif_valor = Convert.ToDecimal(lblValorTotal.Text);
                            }


                            int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                            ft.Ordem = Ordem;

                            ft.Paxs = Convert.ToInt32(ViewState["Paying"]) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                            ft.Paying_Pax = Convert.ToInt32(ViewState["Paying"]) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                            ft.Supp_Paying_Pax = Convert.ToInt32(ViewState["Paying"]) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                            ft.Qtd_Tarifas = Convert.ToInt32(ViewState["Paying"]) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);

                            ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                            ft.S_nome = lblTituloPacote.Text;
                            ft.Categoria = lblCategoria.Text;
                            ft.Room = lblRoom.Text;
                            ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;
                            //ft.NomePacote = lblNomePacote.Text.Trim();

                            if (!lblNomePacote.Text.Equals(""))
                            {
                                ft.NomePacote = lblNomePacote.Text.Trim();
                            }
                            else
                            {
                                ft.NomePacote = null;
                            }


                            if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                            {
                                SupplierDAL sd = new SupplierDAL();
                                MarkupPaisDAL mkd = new MarkupPaisDAL();

                                Supplier spp = sd.ObterPorId(Convert.ToInt32(lblSupplierId.Text));
                                MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                                ft.markup = mkp.Markup;
                                ft.desconto = mkp.Desconto;
                                ft.markupNet = markupcliente;
                                ft.descontoNet = descontocliente;
                            }
                            else
                            {
                                ft.markup = markupcliente;
                                ft.desconto = descontocliente;
                                ft.markupNet = 0;
                                ft.descontoNet = 0;
                            }

                            ft.Data_From = dataPeriodo;

                            int i = 0;
                            ViewState["verify"] = dataPeriodo;

                            while (IsBetween(DayIn, DayOut, Convert.ToDateTime(ViewState["verify"]).DayOfWeek))
                            {
                                i += 1;
                                ViewState["verify"] = Convert.ToDateTime(ViewState["verify"]).AddDays(1);

                                DayOfWeek teste01 = Convert.ToDateTime(ViewState["verify"]).DayOfWeek;

                                //if (DayIn == Convert.ToDateTime(txtDataPeriodoOutHotel.Text).DayOfWeek)
                                //{
                                //    break;
                                //}
                                if (Convert.ToDateTime(txtDataPeriodoOutHotel.Text).DayOfWeek == Convert.ToDateTime(ViewState["verify"]).DayOfWeek)
                                {
                                    break;
                                }
                            }

                            if (IsBetween(DayIn, DayOut, Convert.ToDateTime(txtDataPeriodoInHotel.Text).DayOfWeek))
                            {
                                //i = i - 1;
                                ft.Data_To = Convert.ToDateTime(txtDataPeriodoInHotel.Text).AddDays(i);
                            }
                            //else
                            //{
                            //    i = i - 1;
                            //    ft.Data_To = Convert.ToDateTime(txtDataPeriodoInHotel.Text).AddDays(i);
                            //}

                            ViewState["Count"] = i;

                            double NumNoites = (Convert.ToDateTime(ft.Data_To) - Convert.ToDateTime(ft.Data_From)).TotalDays;

                            if (NumNoites == 0.0)
                            {
                                NumNoites = 1;
                            }

                            ft.Categoria_id = Convert.ToInt32(lblCategoriaId.Text);
                            ft.Room_id = Convert.ToInt32(lblRoomId.Text);
                            ft.S_id = Convert.ToInt32(lblSupplierId.Text);
                            ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);
                            ft.S_email = lblEmailSupplier.Text;
                            ft.Status = "OR";
                            ft.NumNoites = Convert.ToInt32(NumNoites);
                            ft.FTC = false;

                            ftd.Salvar(ft);


                            ddlQtd.SelectedValue = "0";
                        }

                    }


                }

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void AdicionaQtoDiff(decimal markupcliente, decimal descontocliente, DateTime dataPeriodo)
        {
            try
            {
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                DateTime dataPeriodoout = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);

                foreach (DataListItem item in DataListHoteis.Items)
                {
                    DataList DataListHoteisTarifas = (DataList)item.FindControl("DataListHoteisTarifas");

                    Label lblTituloPacote = (Label)item.FindControl("lblTituloPacote");
                    Label lblFDS = (Label)item.FindControl("lblFDS");
                    Label lblNomePacote = (Label)item.FindControl("lblNomePacote");

                    string[] FDSs = lblFDS.Text.ToString().Split('/');

                    DayOfWeek DayIn = ReturnDayPT(FDSs[0].Trim());
                    DayOfWeek DayOut = ReturnDayPT(FDSs[1].Trim());


                    foreach (DataListItem item2 in DataListHoteisTarifas.Items)
                    {
                        Label lblIdTarifa = (Label)item2.FindControl("lblIdTarifa");
                        DropDownList ddlQtd = (DropDownList)item2.FindControl("ddlQtd");
                        Label lblValorTotal = (Label)item2.FindControl("lblValorTotal");
                        Label lblRoom = (Label)item2.FindControl("lblRoom");
                        Label lblMoeda = (Label)item2.FindControl("lblMoeda");
                        Label lblCategoria = (Label)item2.FindControl("lblCategoria");
                        Label lblCategoriaId = (Label)item2.FindControl("lblCategoriaId");
                        Label lblRoomId = (Label)item2.FindControl("lblRoomId");
                        Label lblSupplierId = (Label)item2.FindControl("lblSupplierId");
                        Label lblEmailSupplier = (Label)item2.FindControl("lblEmailSupplier");
                        Label lblMoedaId = (Label)item2.FindControl("lblMoedaId");

                        if (lblCategoria.Text.Equals(ViewState["CategoriaVer"]) && lblRoom.Text.Equals(ViewState["RoomVer"]) && IsBetween(DayIn, DayOut, dataPeriodo.DayOfWeek))
                        {

                            //if (IsBetween(DayIn, DayOut, dataPeriodo.DayOfWeek))
                            //{                               

                            File_Tarifas ft = new File_Tarifas();
                            TipoRoomDAL trd = new TipoRoomDAL();
                            MoedaDAL mod = new MoedaDAL();
                            CambioDAL cambDal = new CambioDAL();
                            PeriodosDAL pdao = new PeriodosDAL();

                            MercadoTarifaDAL mtdal = new MercadoTarifaDAL();

                            S_Mercado_Tarifa smerctariff = mtdal.ObterPorId(Convert.ToInt32(lblIdTarifa.Text));

                            S_Mercado_Periodo smper = pdao.ObterPorIdPeriodo(smerctariff.S_merc_periodo_id);

                            ft.FdsFrom = smper.S_merc_periodo_fdsFrom;
                            ft.FdsTo = smper.S_merc_periodo_fdsTo;

                            decimal valorComCambio;
                            decimal valor = 0;

                            if (lblMoedaId.Text != ddlMoeda.SelectedValue)
                            {
                                Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(lblMoedaId.Text), Convert.ToInt32(ddlMoeda.SelectedValue));

                                valor = Convert.ToDecimal(lblValorTotal.Text);
                                valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                                //if (smerctariff.S_merc_tarif_porApartamento == true)
                                //{
                                //    valor = Convert.ToDecimal(lblValorTotal.Text) / Convert.ToDecimal(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                                //    valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);
                                //}
                                //else
                                //{
                                //    valor = Convert.ToDecimal(lblValorTotal.Text);
                                //    valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);
                                //}


                                ft.S_merc_tarif_valor = valorComCambio;
                            }
                            else
                            {
                                //if (smerctariff.S_merc_tarif_porApartamento == true)
                                //{
                                //    valor = Convert.ToDecimal(lblValorTotal.Text) / Convert.ToDecimal(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                                //    ft.S_merc_tarif_valor = valor;
                                //}
                                //else
                                //{
                                //    ft.S_merc_tarif_valor = Convert.ToDecimal(lblValorTotal.Text);
                                //}

                                ft.S_merc_tarif_valor = Convert.ToDecimal(lblValorTotal.Text);
                            }


                            int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                            ft.Ordem = Ordem;

                            //ft.S_merc_tarif_valor = Convert.ToDecimal(lblValorTotal.Text) / Convert.ToDecimal(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                            ft.Paxs = Convert.ToInt32(ViewState["Paying"]) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                            ft.Paying_Pax = Convert.ToInt32(ViewState["Paying"]) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                            ft.Supp_Paying_Pax = Convert.ToInt32(ViewState["Paying"]) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                            ft.Qtd_Tarifas = Convert.ToInt32(ViewState["Paying"]) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);

                            ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                            ft.S_nome = lblTituloPacote.Text;
                            ft.Categoria = lblCategoria.Text;
                            ft.Room = lblRoom.Text;
                            ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;
                            //ft.NomePacote = lblNomePacote.Text.Trim();

                            if (!lblNomePacote.Text.Equals(""))
                            {
                                ft.NomePacote = lblNomePacote.Text.Trim();
                            }
                            else
                            {
                                ft.NomePacote = null;
                            }


                            if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                            {
                                SupplierDAL sd = new SupplierDAL();
                                MarkupPaisDAL mkd = new MarkupPaisDAL();

                                Supplier spp = sd.ObterPorId(Convert.ToInt32(lblSupplierId.Text));
                                MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                                ft.markup = mkp.Markup;
                                ft.desconto = mkp.Desconto;
                                ft.markupNet = markupcliente;
                                ft.descontoNet = descontocliente;
                            }
                            else
                            {
                                ft.markup = markupcliente;
                                ft.desconto = descontocliente;
                                ft.markupNet = 0;
                                ft.descontoNet = 0;
                            }

                            ft.Data_From = dataPeriodo;
                            //ft.Data_To = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);

                            int i = 0;
                            ViewState["verify"] = dataPeriodo;

                            while (IsBetween(DayIn, DayOut, Convert.ToDateTime(ViewState["verify"]).DayOfWeek))
                            {

                                i += 1;
                                ViewState["verify"] = Convert.ToDateTime(ViewState["verify"]).AddDays(1);

                                if (Convert.ToDateTime(ViewState["verify"]).DayOfWeek == Convert.ToDateTime(txtDataPeriodoOutHotel.Text).DayOfWeek)
                                {
                                    break;
                                }

                            }

                            if (IsBetween(DayIn, DayOut, Convert.ToDateTime(txtDataPeriodoInHotel.Text).DayOfWeek))
                            {
                                //i = i - 1;
                                ft.Data_To = Convert.ToDateTime(txtDataPeriodoInHotel.Text).AddDays(i);
                            }

                            ViewState["Count"] = i;

                            double NumNoites = (Convert.ToDateTime(ft.Data_To) - Convert.ToDateTime(ft.Data_From)).TotalDays;

                            if (NumNoites == 0.0)
                            {
                                NumNoites = 1;
                            }

                            ft.Categoria_id = Convert.ToInt32(lblCategoriaId.Text);
                            ft.Room_id = Convert.ToInt32(lblRoomId.Text);
                            ft.S_id = Convert.ToInt32(lblSupplierId.Text);
                            ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);
                            ft.S_email = lblEmailSupplier.Text;
                            ft.Status = "OR";
                            ft.NumNoites = Convert.ToInt32(NumNoites);
                            ft.FTC = false;

                            ftd.Salvar(ft);


                            ddlQtd.SelectedValue = "0";
                            //}


                        }

                    }


                }


            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void AdicionaQtoVerif(decimal markupcliente, decimal descontocliente, DateTime dataPeriodo)
        {
            FileTarifasDAL ftd = new FileTarifasDAL();
            FileCarrinhoDAL fcd = new FileCarrinhoDAL();

            try
            {
                foreach (DataListItem item in DataListHoteis.Items)
                {
                    DataList DataListHoteisTarifas = (DataList)item.FindControl("DataListHoteisTarifas");

                    Label lblTituloPacote = (Label)item.FindControl("lblTituloPacote");
                    Label lblFDS = (Label)item.FindControl("lblFDS");
                    Label lblNomePacote = (Label)item.FindControl("lblNomePacote");

                    string[] FDSs = lblFDS.Text.ToString().Split('/');

                    DayOfWeek DayIn = ReturnDayPT(FDSs[0].Trim());
                    DayOfWeek DayOut = ReturnDayPT(FDSs[1].Trim());


                    foreach (DataListItem item2 in DataListHoteisTarifas.Items)
                    {
                        Label lblIdTarifa = (Label)item2.FindControl("lblIdTarifa");
                        DropDownList ddlQtd = (DropDownList)item2.FindControl("ddlQtd");
                        Label lblValorTotal = (Label)item2.FindControl("lblValorTotal");
                        Label lblRoom = (Label)item2.FindControl("lblRoom");
                        Label lblMoeda = (Label)item2.FindControl("lblMoeda");
                        Label lblCategoria = (Label)item2.FindControl("lblCategoria");
                        Label lblCategoriaId = (Label)item2.FindControl("lblCategoriaId");
                        Label lblRoomId = (Label)item2.FindControl("lblRoomId");
                        Label lblSupplierId = (Label)item2.FindControl("lblSupplierId");
                        Label lblEmailSupplier = (Label)item2.FindControl("lblEmailSupplier");
                        Label lblMoedaId = (Label)item2.FindControl("lblMoedaId");

                        if (lblCategoria.Text.Equals(ViewState["CategoriaVer"]) && lblRoom.Text.Equals(ViewState["RoomVer"]) && IsBetween(DayIn, DayOut, dataPeriodo.AddDays(1).DayOfWeek))
                        {

                            //if (IsBetween(DayIn, DayOut, dataPeriodo.DayOfWeek))
                            //{                               

                            File_Tarifas ft = new File_Tarifas();
                            TipoRoomDAL trd = new TipoRoomDAL();
                            MoedaDAL mod = new MoedaDAL();
                            CambioDAL cambDal = new CambioDAL();
                            PeriodosDAL pdao = new PeriodosDAL();

                            MercadoTarifaDAL mtdal = new MercadoTarifaDAL();

                            S_Mercado_Tarifa smerctariff = mtdal.ObterPorId(Convert.ToInt32(lblIdTarifa.Text));

                            S_Mercado_Periodo smper = pdao.ObterPorIdPeriodo(smerctariff.S_merc_periodo_id);

                            ft.FdsFrom = smper.S_merc_periodo_fdsFrom;
                            ft.FdsTo = smper.S_merc_periodo_fdsTo;

                            decimal valorComCambio;
                            decimal valor = 0;

                            if (lblMoedaId.Text != ddlMoeda.SelectedValue)
                            {
                                Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(lblMoedaId.Text), Convert.ToInt32(ddlMoeda.SelectedValue));


                                //if (smerctariff.S_merc_tarif_porApartamento == true)
                                //{
                                //    valor = Convert.ToDecimal(lblValorTotal.Text) / Convert.ToDecimal(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                                //    valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);
                                //}
                                //else
                                //{
                                //    valor = Convert.ToDecimal(lblValorTotal.Text);
                                //    valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);
                                //}

                                valor = Convert.ToDecimal(lblValorTotal.Text);
                                valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                                ft.S_merc_tarif_valor = valorComCambio;
                            }
                            else
                            {
                                //if (smerctariff.S_merc_tarif_porApartamento == true)
                                //{
                                //    valor = Convert.ToDecimal(lblValorTotal.Text) / Convert.ToDecimal(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                                //    ft.S_merc_tarif_valor = valor;
                                //}
                                //else
                                //{
                                //    ft.S_merc_tarif_valor = Convert.ToDecimal(lblValorTotal.Text);
                                //}

                                ft.S_merc_tarif_valor = Convert.ToDecimal(lblValorTotal.Text);
                            }


                            int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                            ft.Ordem = Ordem;

                            //ft.S_merc_tarif_valor = Convert.ToDecimal(lblValorTotal.Text) / Convert.ToDecimal(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                            ft.Paxs = Convert.ToInt32(ViewState["Paying"]) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                            ft.Paying_Pax = Convert.ToInt32(ViewState["Paying"]) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                            ft.Supp_Paying_Pax = Convert.ToInt32(ViewState["Paying"]) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                            ft.Qtd_Tarifas = Convert.ToInt32(ViewState["Paying"]) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);

                            ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                            ft.S_nome = lblTituloPacote.Text;
                            ft.Categoria = lblCategoria.Text;
                            ft.Room = lblRoom.Text;
                            ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;
                            //ft.NomePacote = lblNomePacote.Text.Trim();

                            if (!lblNomePacote.Text.Equals(""))
                            {
                                ft.NomePacote = lblNomePacote.Text.Trim();
                            }
                            else
                            {
                                ft.NomePacote = null;
                            }


                            if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                            {
                                SupplierDAL sd = new SupplierDAL();
                                MarkupPaisDAL mkd = new MarkupPaisDAL();

                                Supplier spp = sd.ObterPorId(Convert.ToInt32(lblSupplierId.Text));
                                MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                                ft.markup = mkp.Markup;
                                ft.desconto = mkp.Desconto;
                                ft.markupNet = markupcliente;
                                ft.descontoNet = descontocliente;
                            }
                            else
                            {
                                ft.markup = markupcliente;
                                ft.desconto = descontocliente;
                                ft.markupNet = 0;
                                ft.descontoNet = 0;
                            }

                            ft.Data_From = dataPeriodo;
                            ft.Data_To = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);

                            //int i = 0;
                            //ViewState["verify"] = dataPeriodo;

                            //while (IsBetween(DayIn, DayOut, Convert.ToDateTime(ViewState["verify"]).DayOfWeek))
                            //{
                            //    i += 1;
                            //    ViewState["verify"] = Convert.ToDateTime(ViewState["verify"]).AddDays(1);
                            //}

                            //if (IsBetween(DayIn, DayOut, Convert.ToDateTime(txtDataPeriodoInHotel.Text).DayOfWeek))
                            //{
                            //    i = i - 1;
                            //    ft.Data_To = Convert.ToDateTime(txtDataPeriodoInHotel.Text).AddDays(i);
                            //}

                            //ViewState["Count"] = i;

                            double NumNoites = (Convert.ToDateTime(ft.Data_To) - Convert.ToDateTime(ft.Data_From)).TotalDays;

                            if (NumNoites == 0.0)
                            {
                                NumNoites = 1;
                            }

                            ft.Categoria_id = Convert.ToInt32(lblCategoriaId.Text);
                            ft.Room_id = Convert.ToInt32(lblRoomId.Text);
                            ft.S_id = Convert.ToInt32(lblSupplierId.Text);
                            ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);
                            ft.S_email = lblEmailSupplier.Text;
                            ft.Status = "OR";
                            ft.NumNoites = Convert.ToInt32(NumNoites);
                            ft.FTC = false;

                            ftd.Salvar(ft);



                            //}

                            ddlQtd.SelectedValue = "0";
                        }

                    }


                }

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void ExcluirFileCarrinho(object sender, CommandEventArgs e)
        {
            try
            {

                int myid = Convert.ToInt32(e.CommandArgument);

                FileTarifasDAL ftd = new FileTarifasDAL();

                File_Tarifas ft = ftd.ObterPorId(myid);

                ftd.Excluir(ft);


                MostrarMsg("Registro excluído com sucesso.");
                PopularGridListCarrinho(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                CalculaValorTotal();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void imgAtualizaCarrinhoTarifa_Command(object sender, CommandEventArgs e)
        {
            try
            {

                FileTarifasDAL ftd = new FileTarifasDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                int IdTarifa = Convert.ToInt32(e.CommandArgument);

                foreach (GridViewRow item in GridFileCarrinhoHoteis.Rows)
                {
                    TextBox txtQtdTarifas = (TextBox)item.FindControl("txtQtdTarifas");
                    Label IdFileTarifa = (Label)item.FindControl("IdFileTarifa");
                    TextBox txtDesconto = (TextBox)item.FindControl("txtDesconto");
                    TextBox txtMarkup = (TextBox)item.FindControl("txtMarkup");
                    TextBox txtMarkupNet = (TextBox)item.FindControl("txtMarkupNet");
                    TextBox txtDescontoNet = (TextBox)item.FindControl("txtDescontoNet");
                    TextBox txtValorTarifas = (TextBox)item.FindControl("txtValorTarifas");
                    Label lblPayingPax = (Label)item.FindControl("lblPayingPax");

                    if (IdTarifa == Convert.ToInt32(IdFileTarifa.Text))
                    {
                        File_Tarifas ft = new File_Tarifas();

                        ft.S_merc_tarif_valor = Convert.ToDecimal(txtValorTarifas.Text);
                        ft.markup = Convert.ToDecimal(txtMarkup.Text);
                        ft.markupNet = Convert.ToDecimal(txtMarkupNet.Text);
                        ft.desconto = Convert.ToDecimal(txtDesconto.Text);
                        ft.descontoNet = Convert.ToDecimal(txtDescontoNet.Text);
                        ft.Qtd_Tarifas = Convert.ToInt32(txtQtdTarifas.Text);
                        ft.File_Tarifas_id = IdTarifa;
                        ft.UpdVenda = false;

                        ftd.Atualizar(ft);
                    }

                }


                PopularGridListCarrinho(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                CalculaValorTotal();
                MostrarMsg("File atualizado com sucesso.");

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void imgAtualizaCarrinhoTarifaVenda_Command(object sender, CommandEventArgs e)
        {

            try
            {

                FileTarifasDAL ftd = new FileTarifasDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                int IdTarifa = Convert.ToInt32(e.CommandArgument);

                foreach (GridViewRow item in GridFileCarrinhoHoteis.Rows)
                {
                    TextBox txtQtdTarifas = (TextBox)item.FindControl("txtQtdTarifas");
                    Label IdFileTarifa = (Label)item.FindControl("IdFileTarifa");
                    TextBox txtValorTarifas = (TextBox)item.FindControl("txtValorTarifas");
                    Label lblPayingPax = (Label)item.FindControl("lblPayingPax");
                    Label lblNumNoites = (Label)item.FindControl("lblNumNoites");
                    TextBox txtVenda = (TextBox)item.FindControl("txtVenda");
                    TextBox txtVendaNet = (TextBox)item.FindControl("txtVendaNet");

                    if (IdTarifa == Convert.ToInt32(IdFileTarifa.Text))
                    {
                        File_Tarifas ft = new File_Tarifas();

                        double mult = Convert.ToDouble(txtVenda.Text) * Convert.ToDouble(lblNumNoites.Text);

                        double mkpNew = ((Convert.ToDouble(txtVenda.Text) / Convert.ToDouble(txtValorTarifas.Text)) * 100) - 100;

                        double vlNew = (Convert.ToDouble(txtValorTarifas.Text) * mkpNew) / 100;

                        ft.S_merc_tarif_vendaNet = Convert.ToDecimal(vlNew) + Convert.ToDecimal(txtValorTarifas.Text);
                        ft.markup = Convert.ToDecimal(mkpNew);
                        ft.S_merc_tarif_venda = Convert.ToDecimal(txtVenda.Text);
                        ft.S_merc_tarif_total = Convert.ToDecimal(mult);
                        ft.File_Tarifas_id = IdTarifa;

                        ftd.AtualizarVenda(ft);

                    }

                }

                ViewState["UpdVenda"] = 1;

                PopularGridListCarrinho(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                MostrarMsg("File atualizado com sucesso.");
                CalculaValorTotal();

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }

        }

        protected void VerificaRanges(int IdQuote)
        {
            try
            {

                RangeDal rd = new RangeDal();

                if (rd.ListarTodos(IdQuote).Count() != 0)
                {

                    FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                    int idFile = fcd.RetornaFile(txtQuoteNumber.Text);



                }

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnAddRoomsByBases()
        {
            try
            {
                RangeDal rd = new RangeDal();
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                ClienteDAL cli = new ClienteDAL();

                Quotation q = fcd.RetornaQuoteObj(txtQuoteNumber.Text);


                //if (rd.ListarTodosGroup(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text))).Count() == 0)
                if (q == null)
                {
                    if (txtBaseDeNew.Text.Equals("") || txtBaseAteNew.Text.Equals(""))
                    {
                        MostrarMsg("Selecione uma base inicial para o file.");
                        return;
                    }
                }

                ClienteMarkupDAL climark = new ClienteMarkupDAL();

                DateTime In = Convert.ToDateTime(txtDataPeriodoInHotel.Text);
                DateTime Out = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);

                //double NumNoites = (Out - In).TotalDays;
                double NumNoites = 0;

                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), In);

                decimal markupcliente = 0, descontocliente = 0;

                if (mkfile != null)
                {
                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                    descontocliente = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                }
                else
                {
                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(In);

                    if (mgfile != null)
                    {
                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                        descontocliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                    }
                    else
                    {
                        MostrarMsg("Não existe Markup cadastrado.");
                        return;
                    }
                }

                if (fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])) == null)
                {
                    File_Carrinho fc = new File_Carrinho();

                    fc.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                    fcd.Salvar(fc);
                }

                DateTime dataPeriodo = Convert.ToDateTime(txtDataPeriodoInHotel.Text);
                DateTime dataPeriodoout = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);
                int iCount = 0;
                int Cfds = 0;

                ViewState["verify"] = In;


                foreach (DataListItem item in DataListHoteis.Items)
                {
                    DataList DataListHoteisTarifas = (DataList)item.FindControl("DataListHoteisTarifas");

                    Label lblTituloPacote = (Label)item.FindControl("lblTituloPacote");
                    Label lblFDS = (Label)item.FindControl("lblFDS");
                    Label lblNomePacote = (Label)item.FindControl("lblNomePacote");
                    Label lblEstacao = (Label)item.FindControl("lblEstacao");

                    string[] FDSs = lblFDS.Text.ToString().Split('/');

                    DayOfWeek DayIn = ReturnDayPT(FDSs[0].Trim());
                    DayOfWeek DayOut = ReturnDayPT(FDSs[1].Trim());

                    foreach (DataListItem item2 in DataListHoteisTarifas.Items)
                    {
                        Label lblIdTarifa = (Label)item2.FindControl("lblIdTarifa");
                        DropDownList ddlQtd = (DropDownList)item2.FindControl("ddlQtd");
                        Label lblValorTotal = (Label)item2.FindControl("lblValorTotal");
                        Label lblRoom = (Label)item2.FindControl("lblRoom");
                        Label lblMoeda = (Label)item2.FindControl("lblMoeda");
                        Label lblCategoria = (Label)item2.FindControl("lblCategoria");
                        Label lblCategoriaId = (Label)item2.FindControl("lblCategoriaId");
                        Label lblRoomId = (Label)item2.FindControl("lblRoomId");
                        Label lblSupplierId = (Label)item2.FindControl("lblSupplierId");
                        Label lblEmailSupplier = (Label)item2.FindControl("lblEmailSupplier");
                        Label lblMoedaId = (Label)item2.FindControl("lblMoedaId");



                        if (ddlQtd.SelectedValue != "0")
                        {
                            ViewState["CategoriaVer"] = lblCategoria.Text.Trim();
                            ViewState["RoomVer"] = lblRoom.Text.Trim();
                            ViewState["ValorTotalRoom"] = lblValorTotal.Text.Trim();
                            ViewState["QtdSelectValue"] = ddlQtd.SelectedValue;
                        }


                        if (ddlQtd.SelectedValue != "0")
                        {
                            ViewState["Paying"] = ddlQtd.SelectedValue;
                        }


                        Cfds = 0;

                        if (ddlQtd.SelectedValue != "0")
                        {

                            File_Tarifas ft = new File_Tarifas();
                            TipoRoomDAL trd = new TipoRoomDAL();
                            MoedaDAL mod = new MoedaDAL();
                            CambioDAL cambDal = new CambioDAL();
                            MealDAL mdd = new MealDAL();
                            PeriodosDAL pdao = new PeriodosDAL();

                            MercadoTarifaDAL mtdal = new MercadoTarifaDAL();

                            S_Mercado_Tarifa smerctariff = mtdal.ObterPorId(Convert.ToInt32(lblIdTarifa.Text));

                            S_Mercado_Periodo smper = pdao.ObterPorIdPeriodo(smerctariff.S_merc_periodo_id);

                            List<S_Mercado_Meal> listameals = mdd.ListarAddFile(smerctariff.S_merc_periodo_id);

                            if (smper.MinimoNoites_id != null)
                            {
                                double noites = (Out - In).TotalDays;

                                if (Convert.ToInt32(noites) < smper.MinimoNoites.MinimoNoites_qtd)
                                {
                                    MostrarMsg("Nr. de noites maior que minimo de noites da temporada! Minímo de " + smper.MinimoNoites.MinimoNoites_qtd + "dias");
                                    return;
                                }
                            }

                            ft.FdsFrom = smper.S_merc_periodo_fdsFrom;
                            ft.FdsTo = smper.S_merc_periodo_fdsTo;


                            int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                            ft.Ordem = Ordem;

                            ft.Paxs = Convert.ToInt32(ddlQtd.SelectedValue) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                            ft.Paying_Pax = Convert.ToInt32(ddlQtd.SelectedValue) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                            ft.Supp_Paying_Pax = Convert.ToInt32(ddlQtd.SelectedValue) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                            ft.Qtd_Tarifas = Convert.ToInt32(ddlQtd.SelectedValue) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);


                            ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                            ft.S_nome = lblTituloPacote.Text;
                            ft.Categoria = lblCategoria.Text;
                            ft.Room = lblRoom.Text;
                            ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;

                            if (!lblNomePacote.Text.Equals(""))
                            {
                                ft.NomePacote = lblNomePacote.Text.Trim();
                            }
                            else
                            {
                                ft.NomePacote = null;
                            }


                            ft.Data_From = Convert.ToDateTime(txtDataPeriodoInHotel.Text);
                            ft.Data_To = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);

                            NumNoites = (Convert.ToDateTime(ft.Data_To) - Convert.ToDateTime(ft.Data_From)).TotalDays;

                            if (NumNoites == 0.0)
                            {
                                NumNoites = 1;
                            }

                            ft.Categoria_id = Convert.ToInt32(lblCategoriaId.Text);
                            ft.Room_id = Convert.ToInt32(lblRoomId.Text);
                            ft.S_id = Convert.ToInt32(lblSupplierId.Text);
                            ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);
                            ft.S_email = lblEmailSupplier.Text;
                            ft.Status = "OR";
                            ft.NumNoites = Convert.ToInt32(NumNoites);
                            ft.FTC = false;

                            ft.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                            ftd.Salvar(ft);

                            File_Tarifas ftrange = new File_Tarifas();
                            ftrange.Range_id = 0;
                            ftrange.File_Tarifas_id = ft.File_Tarifas_id;

                            ftd.AtualizarRange(ftrange);

                            bool existe = rd.VerificaExisteRegOpt(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), Convert.ToInt32(ViewState["QuoteAtiva"]));

                            //if (rd.ListarTodosGroup(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text))).Count() > 0)
                            if (existe)
                            {
                                SalvaRangesHoteisExistentes(In, Out, lblRoom.Text, lblCategoria.Text, lblNomePacote.Text, Convert.ToInt32(lblMoedaId.Text), markupcliente, descontocliente, Convert.ToInt32(lblSupplierId.Text), ft.File_Tarifas_id, lblEstacao.Text);
                            }
                            else
                            {
                                SalvaRangesHoteisVazio(In, Out, lblRoom.Text, lblCategoria.Text, lblNomePacote.Text, Convert.ToInt32(lblMoedaId.Text), markupcliente, descontocliente, Convert.ToInt32(lblSupplierId.Text), ft.File_Tarifas_id, lblEstacao.Text);
                            }


                            PopulaNewQuote(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToInt32(ViewState["QuoteAtiva"]));

                            ddlQtd.SelectedValue = "0";
                        }


                    }

                }

                MostrarMsg("Tarifas adicionadas ao file com sucesso.");
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnAddRoomsByBasesDirFile()
        {

            try
            {

                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                ClienteDAL cli = new ClienteDAL();

                QuoteTarifasDAL ftd = new QuoteTarifasDAL();

                Quotation q = fcd.RetornaQuoteObj(txtQuoteNumber.Text);
                if (q == null)
                {
                    if (txtBaseDeNew.Text.Equals("") || txtBaseAteNew.Text.Equals(""))
                    {
                        MostrarMsg("Selecione uma base inicial para o file.");
                        return;
                    }
                }

                ClienteMarkupDAL climark = new ClienteMarkupDAL();

                DateTime In = Convert.ToDateTime(txtDataPeriodoInHotel.Text);
                DateTime Out = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);

                double NumNoites = 0;

                //Cliente_Markup cl = climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue));
                //decimal markupcliente = 0;
                //decimal descontocliente = 0;
                //if (cl == null)
                //{
                //    MostrarMsg("Esse cliente não possui markup cadastrado.");
                //    return;
                //}
                //else
                //{
                //    markupcliente = Convert.ToDecimal(cl.Markup_hotel);
                //    descontocliente = Convert.ToDecimal(cl.Markup_descontoHotel);
                //}

                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), In);
                decimal markupcliente = 0, descontocliente = 0;
                if (mkfile != null)
                {
                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                    descontocliente = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                }
                else
                {
                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(In);

                    if (mgfile != null)
                    {
                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                        descontocliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                    }
                    else
                    {
                        MostrarMsg("Não existe Markup cadastrado.");
                        return;
                    }
                }

                if (fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])) == null)
                {
                    File_Carrinho fc = new File_Carrinho();

                    fc.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                    fcd.Salvar(fc);
                }

                DateTime dataPeriodo = Convert.ToDateTime(txtDataPeriodoInHotel.Text);
                DateTime dataPeriodoout = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);
                int iCount = 0;
                int Cfds = 0;

                ViewState["verify"] = In;


                foreach (DataListItem item in DataListHoteis.Items)
                {
                    DataList DataListHoteisTarifas = (DataList)item.FindControl("DataListHoteisTarifas");

                    Label lblTituloPacote = (Label)item.FindControl("lblTituloPacote");
                    Label lblFDS = (Label)item.FindControl("lblFDS");
                    Label lblNomePacote = (Label)item.FindControl("lblNomePacote");

                    string[] FDSs = lblFDS.Text.ToString().Split('/');

                    DayOfWeek DayIn = ReturnDayPT(FDSs[0].Trim());
                    DayOfWeek DayOut = ReturnDayPT(FDSs[1].Trim());

                    foreach (DataListItem item2 in DataListHoteisTarifas.Items)
                    {
                        Label lblIdTarifa = (Label)item2.FindControl("lblIdTarifa");
                        DropDownList ddlQtd = (DropDownList)item2.FindControl("ddlQtd");
                        Label lblValorTotal = (Label)item2.FindControl("lblValorTotal");
                        Label lblRoom = (Label)item2.FindControl("lblRoom");
                        Label lblMoeda = (Label)item2.FindControl("lblMoeda");
                        Label lblCategoria = (Label)item2.FindControl("lblCategoria");
                        Label lblCategoriaId = (Label)item2.FindControl("lblCategoriaId");
                        Label lblRoomId = (Label)item2.FindControl("lblRoomId");
                        Label lblSupplierId = (Label)item2.FindControl("lblSupplierId");
                        Label lblEmailSupplier = (Label)item2.FindControl("lblEmailSupplier");
                        Label lblMoedaId = (Label)item2.FindControl("lblMoedaId");


                        if (ddlQtd.SelectedValue != "0")
                        {
                            ViewState["CategoriaVer"] = lblCategoria.Text.Trim();
                            ViewState["RoomVer"] = lblRoom.Text.Trim();
                            ViewState["ValorTotalRoom"] = lblValorTotal.Text.Trim();
                            ViewState["QtdSelectValue"] = ddlQtd.SelectedValue;
                        }


                        if (ddlQtd.SelectedValue != "0")
                        {
                            ViewState["Paying"] = ddlQtd.SelectedValue;
                        }


                        Cfds = 0;

                        if (ddlQtd.SelectedValue != "0")
                        {
                            Cfds = 0;

                            Quote_Tarifas ft = new Quote_Tarifas();
                            TipoRoomDAL trd = new TipoRoomDAL();
                            MoedaDAL mod = new MoedaDAL();
                            CambioDAL cambDal = new CambioDAL();
                            MealDAL mdd = new MealDAL();
                            PeriodosDAL pdao = new PeriodosDAL();

                            MercadoTarifaDAL mtdal = new MercadoTarifaDAL();

                            S_Mercado_Tarifa smerctariff = mtdal.ObterPorId(Convert.ToInt32(lblIdTarifa.Text));

                            List<S_Mercado_Meal> listameals = mdd.ListarAddFile(smerctariff.S_merc_periodo_id);

                            S_Mercado_Periodo smper = pdao.ObterPorIdPeriodo(smerctariff.S_merc_periodo_id);

                            if (smper.MinimoNoites_id != null)
                            {
                                double noites = (Out - In).TotalDays;

                                if (Convert.ToInt32(noites) < smper.MinimoNoites.MinimoNoites_qtd)
                                {
                                    MostrarMsg("Nr. de noites maior que minimo de noites da temporada! Minímo de " + smper.MinimoNoites.MinimoNoites_qtd + "dias");
                                    return;
                                }
                            }

                            ft.FdsFrom = smper.S_merc_periodo_fdsFrom;
                            ft.FdsTo = smper.S_merc_periodo_fdsTo;

                            decimal valorComCambio;
                            decimal valor = 0;

                            if (lblValorTotal.Text.Equals(""))
                            {

                                ft.S_merc_tarif_valor = 0;

                            }
                            else
                            {
                                if (lblMoedaId.Text != ddlMoeda.SelectedValue)
                                {
                                    Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(lblMoedaId.Text), Convert.ToInt32(ddlMoeda.SelectedValue));

                                    valor = Convert.ToDecimal(lblValorTotal.Text);
                                    valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                                    ft.S_merc_tarif_valor = valorComCambio;
                                }
                                else
                                {

                                    ft.S_merc_tarif_valor = Convert.ToDecimal(lblValorTotal.Text);
                                }
                            }

                            int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                            ft.Ordem = Ordem;

                            ft.Paxs = Convert.ToInt32(ddlQtd.SelectedValue) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                            ft.Paying_Pax = Convert.ToInt32(ddlQtd.SelectedValue) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                            ft.Supp_Paying_Pax = Convert.ToInt32(ddlQtd.SelectedValue) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);
                            ft.Qtd_Tarifas = Convert.ToInt32(ddlQtd.SelectedValue) * Convert.ToInt32(trd.ObterPorId(Convert.ToInt32(lblRoomId.Text)).Tipo_room_number);


                            ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                            ft.S_nome = lblTituloPacote.Text;
                            ft.Categoria = lblCategoria.Text;
                            ft.Room = lblRoom.Text;
                            ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;

                            if (!lblNomePacote.Text.Equals(""))
                            {
                                ft.NomePacote = lblNomePacote.Text.Trim();
                            }
                            else
                            {
                                ft.NomePacote = null;
                            }



                            if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                            {
                                SupplierDAL sd = new SupplierDAL();
                                MarkupPaisDAL mkd = new MarkupPaisDAL();

                                Supplier spp = sd.ObterPorId(Convert.ToInt32(lblSupplierId.Text));
                                MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                                ft.markup = mkp.Markup;
                                ft.desconto = mkp.Desconto;
                                ft.markupNet = markupcliente;
                                ft.descontoNet = descontocliente;
                            }
                            else
                            {
                                ft.markup = markupcliente;
                                ft.desconto = descontocliente;
                                ft.markupNet = 0;
                                ft.descontoNet = 0;
                            }


                            ft.Data_From = Convert.ToDateTime(txtDataPeriodoInHotel.Text);
                            ft.Data_To = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);

                            NumNoites = (Convert.ToDateTime(ft.Data_To) - Convert.ToDateTime(ft.Data_From)).TotalDays;

                            if (NumNoites == 0.0)
                            {
                                NumNoites = 1;
                            }

                            ft.Categoria_id = Convert.ToInt32(lblCategoriaId.Text);
                            ft.Room_id = Convert.ToInt32(lblRoomId.Text);
                            ft.S_id = Convert.ToInt32(lblSupplierId.Text);
                            ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);
                            ft.S_email = lblEmailSupplier.Text;
                            ft.Status = "OR";
                            ft.NumNoites = Convert.ToInt32(NumNoites);
                            ft.FTC = false;
                            ft.Flag = "hotel";
                            ft.Range_id = 0;

                            if (flagTC == 0) ft.TC = false; else ft.TC = true;

                            if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("N"))
                            {
                                DescricaoDAL dd = new DescricaoDAL();

                                string remark;

                                if (dd.ObterPorIdSupp(Convert.ToInt32(lblSupplierId.Text)) != null)
                                {
                                    remark = dd.ObterPorIdSupp(Convert.ToInt32(lblSupplierId.Text)).Desc_remarks;
                                }
                                else
                                {
                                    remark = "No remarks";
                                }

                                lblMsgOperador.Text = remark;
                                ModalPopupExtenderMsgOperador.Show();
                            }

                            ftd.Salvar(ft);

                            if (flagTC == 0)
                            {
                                if (!fcd.VerificaExisteTCQuotes(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))))
                                {
                                    ddlQtd.SelectedValue = "0";
                                }
                            }
                            else
                            {
                                ddlQtd.SelectedValue = "0";
                            }

                            AcertaRangeDirFile(ft.Quote_Tarifas_id, "hotel");

                            PopularNewFile();
                        }


                    }

                }

                if (flagTC == 0)
                {
                    if (fcd.VerificaExisteTCQuotes(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))))
                    {
                        flagTC = 1;
                        btnAddRoomsByBasesDirFile();
                    }
                }
                else
                {
                    flagTC = 0;
                }

                MostrarMsg("Tarifas adicionadas ao file com sucesso.");
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnAddRoomsMealByBases(int e)
        {
            try
            {

                FileTarifasDAL ftd = new FileTarifasDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                ClienteDAL cli = new ClienteDAL();

                ClienteMarkupDAL climark = new ClienteMarkupDAL();

                Quotation q = fcd.RetornaQuoteObj(txtQuoteNumber.Text);
                if (q == null)
                {
                    if (txtBaseDeNew.Text.Equals("") || txtBaseAteNew.Text.Equals(""))
                    {
                        MostrarMsg("Selecione uma base inicial para o file.");
                        return;
                    }
                }

                DateTime In = Convert.ToDateTime(txtDataPeriodoInHotel.Text);
                DateTime Out = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);
                double NumNoites = 0;

                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), In);
                decimal markupcliente = 0, descontocliente = 0;
                if (mkfile != null)
                {
                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                    descontocliente = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                }
                else
                {
                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(In);

                    if (mgfile != null)
                    {
                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                        descontocliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                    }
                    else
                    {
                        MostrarMsg("Não existe Markup cadastrado.");
                        return;
                    }
                }

                //decimal markupcliente = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_hotel);
                //decimal descontocliente = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_descontoHotel);

                if (fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])) == null)
                {
                    File_Carrinho fc = new File_Carrinho();

                    fc.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                    fcd.Salvar(fc);
                }


                DateTime dataPeriodo = Convert.ToDateTime(txtDataPeriodoInHotel.Text);
                int iCount = 0;
                int Cfds = 0;

                foreach (DataListItem item in DataListHoteis.Items)
                {
                    DataList DataListHoteisMeals = (DataList)item.FindControl("DataListHoteisMeals");

                    Label lblTituloPacote = (Label)item.FindControl("lblTituloPacote");
                    Label lblFDS = (Label)item.FindControl("lblFDS");
                    Label lblNomePacote = (Label)item.FindControl("lblNomePacote");

                    string[] FDSs = lblFDS.Text.ToString().Split('/');

                    DayOfWeek DayIn = ReturnDayPT(FDSs[0].Trim());
                    DayOfWeek DayOut = ReturnDayPT(FDSs[1].Trim());

                    foreach (DataListItem item2 in DataListHoteisMeals.Items)
                    {
                        Label lblMoedaMeal = (Label)item2.FindControl("lblMoedaMeal");
                        Label lblMoedaId = (Label)item2.FindControl("lblMoedaId");
                        Label lblValorTotalMeal = (Label)item2.FindControl("lblValorTotalMeal");
                        Label lblMealId = (Label)item2.FindControl("lblMealId");
                        Label lblMealNome = (Label)item2.FindControl("lblMealNome");
                        Label lblStatusMeal = (Label)item2.FindControl("lblStatusMeal");
                        Label lblSupplierMealId = (Label)item2.FindControl("lblSupplierMealId");

                        Cfds = 0;

                        bool jaAdd = ftd.VerificaMeal(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"])), Convert.ToInt32(lblMealId.Text));

                        if (Convert.ToInt32(lblMealId.Text) == Convert.ToInt32(e) && !jaAdd)
                        {
                            File_Tarifas ft = new File_Tarifas();
                            MoedaDAL mod = new MoedaDAL();
                            CambioDAL cambDal = new CambioDAL();
                            MealDAL md = new MealDAL();
                            RangeDal rd = new RangeDal();

                            S_Mercado_Meal smercmeal = md.ObterPorId(Convert.ToInt32(lblMealId.Text));

                            decimal valorComCambio;
                            decimal valor = 0;


                            if (!lblStatusMeal.Text.Equals(""))
                            {
                                ft.S_meal_status = lblStatusMeal.Text;
                            }

                            int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                            ft.Ordem = Ordem;

                            ft.Paxs = Convert.ToInt32(ddlAdultos.SelectedValue);
                            ft.Paying_Pax = Convert.ToInt32(ddlAdultos.SelectedValue);
                            ft.Supp_Paying_Pax = Convert.ToInt32(ddlAdultos.SelectedValue);
                            ft.Qtd_Tarifas = Convert.ToInt32(ddlAdultos.SelectedValue);

                            ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                            ft.S_meal_nome = lblMealNome.Text;
                            ft.S_meal_id = Convert.ToInt32(lblMealId.Text);
                            ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;

                            SupplierDAL sd = new SupplierDAL();
                            MarkupPaisDAL mkd = new MarkupPaisDAL();

                            Supplier spp = sd.ObterPorId(Convert.ToInt32(lblSupplierMealId.Text));


                            ft.Data_From = Convert.ToDateTime(txtDataPeriodoInHotel.Text);
                            ft.Data_To = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);

                            NumNoites = (Convert.ToDateTime(ft.Data_To) - Convert.ToDateTime(ft.Data_From)).TotalDays;

                            if (NumNoites == 0.0)
                            {
                                NumNoites = 1;
                            }

                            ft.S_id = Convert.ToInt32(lblSupplierMealId.Text);
                            ft.S_nome = lblTituloPacote.Text;
                            ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);
                            ft.S_email = spp.S_email;
                            ft.Meal = true;
                            ft.Status = "OR";

                            ft.NumNoites = Convert.ToInt32(NumNoites);
                            ft.FTC = false;

                            ft.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                            ftd.Salvar(ft);

                            File_Tarifas ftrange = new File_Tarifas();
                            ftrange.Range_id = 0;
                            ftrange.File_Tarifas_id = ft.File_Tarifas_id;

                            ftd.AtualizarRange(ftrange);

                            //if (rd.ListarTodosGroup(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text))).Count() > 0)
                            if (rd.VerificaExisteRegOpt(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), Convert.ToInt32(ViewState["QuoteAtiva"])))
                            {
                                SalvaRangesMealExistentes(lblStatusMeal.Text, Convert.ToInt32(lblMealId.Text), In, Out, Convert.ToInt32(lblMoedaId.Text),
                                                           markupcliente, descontocliente, Convert.ToInt32(lblSupplierMealId.Text), lblValorTotalMeal.Text,
                                                           ft.File_Tarifas_id);
                            }
                            else
                            {
                                SalvaRangesMealVazio(lblStatusMeal.Text, Convert.ToInt32(lblMealId.Text), In, Out, Convert.ToInt32(lblMoedaId.Text),
                                                           markupcliente, descontocliente, Convert.ToInt32(lblSupplierMealId.Text), lblValorTotalMeal.Text,
                                                           ft.File_Tarifas_id);
                            }

                            PopulaNewQuote(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToInt32(ViewState["QuoteAtiva"]));
                        }

                    }

                }

                //PopularGridListCarrinho(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                //CalculaValorTotal();
                MostrarMsg("Tarifas adicionadas ao file com sucesso.");

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnAddRoomsMealByBasesDirFile(int e)
        {
            try
            {

                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                ClienteDAL cli = new ClienteDAL();

                QuoteTarifasDAL ftd = new QuoteTarifasDAL();

                Quotation q = fcd.RetornaQuoteObj(txtQuoteNumber.Text);
                if (q == null)
                {
                    if (txtBaseDeNew.Text.Equals("") || txtBaseAteNew.Text.Equals(""))
                    {
                        MostrarMsg("Selecione uma base inicial para o file.");
                        return;
                    }
                }

                ClienteMarkupDAL climark = new ClienteMarkupDAL();

                DateTime In = Convert.ToDateTime(txtDataPeriodoInHotel.Text);
                DateTime Out = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);

                double NumNoites = 0;

                //Cliente_Markup cl = climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue));
                //decimal markupcliente = 0;
                //decimal descontocliente = 0;
                //if (cl == null)
                //{
                //    MostrarMsg("Esse cliente não possui markup cadastrado.");
                //    return;
                //}
                //else
                //{
                //    markupcliente = Convert.ToDecimal(cl.Markup_hotel);
                //    descontocliente = Convert.ToDecimal(cl.Markup_descontoHotel);
                //}

                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), In);
                decimal markupcliente = 0, descontocliente = 0;
                if (mkfile != null)
                {
                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                    descontocliente = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                }
                else
                {
                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(In);

                    if (mgfile != null)
                    {
                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                        descontocliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                    }
                    else
                    {
                        MostrarMsg("Não existe Markup cadastrado.");
                        return;
                    }
                }

                if (fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])) == null)
                {
                    File_Carrinho fc = new File_Carrinho();

                    fc.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                    fcd.Salvar(fc);
                }


                DateTime dataPeriodo = Convert.ToDateTime(txtDataPeriodoInHotel.Text);

                foreach (DataListItem item in DataListHoteis.Items)
                {
                    DataList DataListHoteisMeals = (DataList)item.FindControl("DataListHoteisMeals");

                    Label lblTituloPacote = (Label)item.FindControl("lblTituloPacote");
                    Label lblFDS = (Label)item.FindControl("lblFDS");
                    Label lblNomePacote = (Label)item.FindControl("lblNomePacote");

                    string[] FDSs = lblFDS.Text.ToString().Split('/');

                    DayOfWeek DayIn = ReturnDayPT(FDSs[0].Trim());
                    DayOfWeek DayOut = ReturnDayPT(FDSs[1].Trim());

                    foreach (DataListItem item2 in DataListHoteisMeals.Items)
                    {
                        Label lblMoedaMeal = (Label)item2.FindControl("lblMoedaMeal");
                        Label lblMoedaId = (Label)item2.FindControl("lblMoedaId");
                        Label lblValorTotalMeal = (Label)item2.FindControl("lblValorTotalMeal");
                        Label lblMealId = (Label)item2.FindControl("lblMealId");
                        Label lblMealNome = (Label)item2.FindControl("lblMealNome");
                        Label lblStatusMeal = (Label)item2.FindControl("lblStatusMeal");
                        Label lblSupplierMealId = (Label)item2.FindControl("lblSupplierMealId");

                        //Cfds = 0;

                        bool jaAdd = ftd.VerificaMeal(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"])), Convert.ToInt32(lblMealId.Text));

                        if (Convert.ToInt32(lblMealId.Text) == Convert.ToInt32(e) && !jaAdd)
                        {
                            Quote_Tarifas ft = new Quote_Tarifas();
                            MoedaDAL mod = new MoedaDAL();
                            CambioDAL cambDal = new CambioDAL();
                            MealDAL md = new MealDAL();

                            S_Mercado_Meal smercmeal = md.ObterPorId(Convert.ToInt32(lblMealId.Text));

                            decimal valorComCambio;
                            decimal valor = 0;

                            if (!lblStatusMeal.Text.Equals(""))
                            {
                                ft.S_meal_status = lblStatusMeal.Text;
                            }
                            else
                            {
                                if (lblMoedaId.Text != ddlMoeda.SelectedValue)
                                {
                                    Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(lblMoedaId.Text), Convert.ToInt32(ddlMoeda.SelectedValue));

                                    valor = Convert.ToDecimal(lblValorTotalMeal.Text);
                                    valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                                    ft.S_merc_tarif_valor = valorComCambio;
                                }
                                else
                                {
                                    ft.S_merc_tarif_valor = Convert.ToDecimal(lblValorTotalMeal.Text);
                                }
                            }

                            int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                            ft.Ordem = Ordem;

                            ft.Paxs = Convert.ToInt32(ddlAdultos.SelectedValue);
                            ft.Paying_Pax = Convert.ToInt32(ddlAdultos.SelectedValue);
                            ft.Supp_Paying_Pax = Convert.ToInt32(ddlAdultos.SelectedValue);
                            ft.Qtd_Tarifas = Convert.ToInt32(ddlAdultos.SelectedValue);

                            ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                            ft.S_meal_nome = lblMealNome.Text;
                            ft.S_meal_id = Convert.ToInt32(lblMealId.Text);
                            ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;

                            SupplierDAL sd = new SupplierDAL();
                            MarkupPaisDAL mkd = new MarkupPaisDAL();

                            Supplier spp = sd.ObterPorId(Convert.ToInt32(lblSupplierMealId.Text));

                            if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                            {
                                MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                                if (lblStatusMeal.Text.Equals(""))
                                {
                                    ft.markup = mkp.Markup;
                                    ft.desconto = mkp.Desconto;
                                    ft.markupNet = markupcliente;
                                    ft.descontoNet = descontocliente;
                                }
                                else
                                {
                                    ft.markup = 0;
                                    ft.desconto = 0;
                                    ft.markupNet = 0;
                                    ft.descontoNet = 0;
                                }
                            }
                            else
                            {
                                if (lblStatusMeal.Text.Equals(""))
                                {
                                    ft.markup = markupcliente;
                                    ft.desconto = descontocliente;
                                    ft.markupNet = 0;
                                    ft.descontoNet = 0;
                                }
                                else
                                {
                                    ft.markup = 0;
                                    ft.desconto = 0;
                                    ft.markupNet = 0;
                                    ft.descontoNet = 0;
                                }
                            }


                            ft.Data_From = Convert.ToDateTime(txtDataPeriodoInHotel.Text);
                            ft.Data_To = Convert.ToDateTime(txtDataPeriodoOutHotel.Text);

                            NumNoites = (Convert.ToDateTime(ft.Data_To) - Convert.ToDateTime(ft.Data_From)).TotalDays;

                            if (NumNoites == 0.0)
                            {
                                NumNoites = 1;
                            }

                            ft.S_id = Convert.ToInt32(lblSupplierMealId.Text);
                            ft.S_nome = lblTituloPacote.Text;
                            ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);
                            ft.S_email = spp.S_email;
                            ft.Meal = true;
                            ft.Status = "OR";

                            ft.NumNoites = Convert.ToInt32(NumNoites);
                            ft.FTC = false;

                            ft.Flag = "hotel";
                            ft.Range_id = 0;
                            if (flagTC == 0) ft.TC = false; else ft.TC = true;

                            ftd.Salvar(ft);

                            AcertaRangeDirFile(ft.Quote_Tarifas_id, "hotel");
                            PopularNewFile();
                        }
                    }

                }

                if (flagTC == 0)
                {
                    if (fcd.VerificaExisteTCQuotes(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))))
                    {
                        flagTC = 1;
                        btnAddRoomsMealByBasesDirFile(e);
                    }
                }
                else
                {
                    flagTC = 0;
                }

                MostrarMsg("Tarifas adicionadas ao file com sucesso.");

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void SalvaRangesHoteisExistentes(DateTime dtFrom, DateTime dtTo, string room, string categoria, string nomePacote, int IdMoeda, decimal markupcliente, decimal descontocliente, int IdSupplier, int IdTarifa, string estacao)
        {
            try
            {

                RangeDal rd = new RangeDal();
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                CambioDAL cambDal = new CambioDAL();
                TipoRoomDAL trd = new TipoRoomDAL();

                int IdQuot = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));

                int num = 0;
                bool exists2;
                List<string> BasesAdicionadas2 = new List<string>();
                List<int> RangesID = new List<int>();
                List<int> ids = new List<int>();

                foreach (Ranges rgs in rd.ListarTodos(IdQuot, Convert.ToInt32(ViewState["QuoteAtiva"])))
                {

                    if (!rgs.Ranges_de.Equals("TC"))
                    {
                        exists2 = BasesAdicionadas2.Exists(element => element.Equals(rgs.Ranges_de));
                        num = 1;
                    }
                    else
                    {
                        exists2 = false;
                    }

                    if (!exists2 && num == 1)
                    {
                        BasesAdicionadas2.Add(rgs.Ranges_de);

                        if (rgs.Ranges_de.Equals("TC"))
                        {
                            num = 0;
                        }

                        int[] arrayOf = ids.ToArray();

                        Ranges range = new Ranges();
                        range.Ranges_de = rgs.Ranges_de;
                        range.Ranges_ate = rgs.Ranges_ate;
                        range.Quotation_Id = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));
                        range.Flag = "hotel";

                        range.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                        if (rd.ObterPorTarifaOne(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), rgs.Ranges_de, rgs.Ranges_ate) != null)
                        {
                            range.Ordem = rd.ObterPorTarifaOne(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), rgs.Ranges_de, rgs.Ranges_ate).Ordem;
                        }
                        else
                        {
                            range.Ordem = rd.ObterPorTarifaLast(IdTarifa).Ordem + 1;
                        }

                        if (rgs.Ranges_de.Equals("TC", StringComparison.OrdinalIgnoreCase))
                        {
                            range.RangeID = arrayOf[0];

                            int numToRemove = arrayOf[0];
                            arrayOf = arrayOf.Where(val => val != numToRemove).ToArray();
                            ids.Clear();
                        }

                        decimal valorComCambio;
                        decimal valor = 0;

                        TarifaDAL td = new TarifaDAL();

                        S_Mercado_Tarifa smt = td.ObterTarifa(IdSupplier, dtFrom,
                                                                      dtTo, room, categoria, nomePacote);

                        if (smt != null)
                        {
                            if (IdMoeda.ToString() != ddlMoeda.SelectedValue)
                            {
                                Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(IdMoeda), Convert.ToInt32(ddlMoeda.SelectedValue));

                                valor = Convert.ToDecimal(smt.S_merc_tarif_tarifa_total);

                                if (smt.S_merc_tarif_porApartamento == true)
                                {
                                    valor = valor / Convert.ToDecimal(trd.ObterPorNome(room).Tipo_room_number);
                                    valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);
                                }
                                else
                                {
                                    valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);
                                }

                                range.Valor = valorComCambio;
                            }
                            else
                            {
                                valor = Convert.ToDecimal(smt.S_merc_tarif_tarifa_total);

                                if (smt.S_merc_tarif_porApartamento == true)
                                {
                                    range.Valor = valor / Convert.ToDecimal(trd.ObterPorNome(room).Tipo_room_number);
                                }
                                else
                                {
                                    range.Valor = valor;
                                }

                            }
                        }
                        else
                        {
                            range.Valor = 0;
                        }

                        //if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        //{
                        SupplierDAL sd = new SupplierDAL();
                        MarkupPaisDAL mkd = new MarkupPaisDAL();

                        Supplier spp = sd.ObterPorId(Convert.ToInt32(IdSupplier));
                        MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                        range.markup = mkp.Markup;
                        range.desconto = mkp.Desconto;
                        range.markupNet = markupcliente;
                        range.descontoNet = descontocliente;
                        //}
                        //else
                        //{
                        //    range.markup = markupcliente;
                        //    range.desconto = descontocliente;
                        //    range.markupNet = 0;
                        //    range.descontoNet = 0;
                        //}

                        range.FileTabelaId = IdTarifa;

                        rd.Salvar(range);

                        if (!range.Ranges_de.Equals("TC", StringComparison.OrdinalIgnoreCase))
                        {
                            ids.Add(range.Ranges_id);
                        }

                        AcertaRange(range.Ranges_id, IdTarifa, range.Flag);

                    }

                }

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void SalvaRangesHoteisVazio(DateTime dtFrom, DateTime dtTo, string room, string categoria, string nomePacote, int IdMoeda, decimal markupcliente, decimal descontocliente, int IdSupplier, int IdTarifa, string estacao)
        {
            try
            {

                RangeDal rd = new RangeDal();
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                CambioDAL cambDal = new CambioDAL();

                Ranges range = new Ranges();
                range.Ranges_de = txtBaseDeNew.Text;
                range.Ranges_ate = txtBaseAteNew.Text;
                range.Quotation_Id = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));
                range.Flag = "hotel";

                range.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                bool existe = rd.VerificaExisteRegOpt(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), Convert.ToInt32(ViewState["QuoteAtiva"]));

                //if (rd.ListarTodosGroup(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text))).Count == 0)
                if (!existe)
                {
                    range.Ordem = 1;
                }
                else
                {
                    range.Ordem = rd.ObterPorTarifaLast(IdTarifa).Ordem + 1;
                }

                decimal valorComCambio;
                decimal valor = 0;

                TarifaDAL td = new TarifaDAL();

                S_Mercado_Tarifa smt = td.ObterTarifa(IdSupplier, dtFrom,
                                                              dtTo, room, categoria, nomePacote);

                if (smt != null)
                {
                    if (IdMoeda.ToString() != ddlMoeda.SelectedValue)
                    {
                        Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(IdMoeda), Convert.ToInt32(ddlMoeda.SelectedValue));

                        valor = Convert.ToDecimal(smt.S_merc_tarif_tarifa_total);
                        valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                        range.Valor = valorComCambio;
                    }
                    else
                    {
                        range.Valor = Convert.ToDecimal(smt.S_merc_tarif_tarifa_total);
                    }
                }
                else
                {
                    range.Valor = 0;
                }

                if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                {
                    SupplierDAL sd = new SupplierDAL();
                    MarkupPaisDAL mkd = new MarkupPaisDAL();

                    Supplier spp = sd.ObterPorId(Convert.ToInt32(IdSupplier));
                    MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                    range.markup = mkp.Markup;
                    range.desconto = mkp.Desconto;
                    range.markupNet = markupcliente;
                    range.descontoNet = descontocliente;
                }
                else
                {
                    range.markup = markupcliente;
                    range.desconto = descontocliente;
                    range.markupNet = 0;
                    range.descontoNet = 0;
                }

                range.FileTabelaId = IdTarifa;

                rd.Salvar(range);

                AcertaRange(range.Ranges_id, IdTarifa, range.Flag);

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void SalvaRangesMealExistentes(string StatusMeal, int IdMeal, DateTime dtFrom, DateTime dtTo, int IdMoeda, decimal markupcliente, decimal descontocliente, int IdSupplier, string valor, int IdTarifa)
        {
            try
            {

                RangeDal rd = new RangeDal();
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                CambioDAL cambDal = new CambioDAL();


                int IdQuot = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));

                int num = 0;
                bool exists2;
                List<string> BasesAdicionadas2 = new List<string>();
                List<int> RangesID = new List<int>();
                List<int> ids = new List<int>();

                foreach (Ranges rgs in rd.ListarTodos(IdQuot, Convert.ToInt32(ViewState["QuoteAtiva"])))
                {

                    if (!rgs.Ranges_de.Equals("TC"))
                    {
                        exists2 = BasesAdicionadas2.Exists(element => element.Equals(rgs.Ranges_de));
                        num = 1;
                    }
                    else
                    {
                        exists2 = false;
                    }

                    if (!exists2 && num == 1)
                    {
                        BasesAdicionadas2.Add(rgs.Ranges_de);

                        if (rgs.Ranges_de.Equals("TC"))
                        {
                            num = 0;
                        }

                        int[] arrayOf = ids.ToArray();
                        Ranges range = new Ranges();
                        range.Ranges_de = rgs.Ranges_de;
                        range.Ranges_ate = rgs.Ranges_ate;
                        range.Quotation_Id = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));
                        range.Flag = "hotel";

                        range.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                        if (rd.ObterPorTarifaOne(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), rgs.Ranges_de, rgs.Ranges_ate) != null)
                        {
                            range.Ordem = rd.ObterPorTarifaOne(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), rgs.Ranges_de, rgs.Ranges_ate).Ordem;
                        }
                        else
                        {
                            range.Ordem = rd.ObterPorTarifaLast(IdTarifa).Ordem + 1;
                        }

                        if (rgs.Ranges_de.Equals("TC", StringComparison.OrdinalIgnoreCase))
                        {
                            range.RangeID = arrayOf[0];

                            int numToRemove = arrayOf[0];
                            arrayOf = arrayOf.Where(val => val != numToRemove).ToArray();
                            ids.Clear();
                        }

                        decimal valorComCambio;
                        decimal valorR = 0;

                        TarifaDAL td = new TarifaDAL();

                        if (StatusMeal.Equals(""))
                        {
                            if (IdMoeda.ToString() != ddlMoeda.SelectedValue)
                            {
                                Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(IdMoeda), Convert.ToInt32(ddlMoeda.SelectedValue));

                                valorR = Convert.ToDecimal(valor);
                                valorComCambio = valorR * Convert.ToDecimal(camb.Cambio1);

                                range.Valor = valorComCambio;
                            }
                            else
                            {
                                range.Valor = Convert.ToDecimal(valor);
                            }
                        }

                        SupplierDAL sd = new SupplierDAL();
                        MarkupPaisDAL mkd = new MarkupPaisDAL();

                        Supplier spp = sd.ObterPorId(Convert.ToInt32(IdSupplier));

                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        {
                            MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                            if (StatusMeal.Equals(""))
                            {
                                range.markup = mkp.Markup;
                                range.desconto = mkp.Desconto;
                                range.markupNet = markupcliente;
                                range.descontoNet = descontocliente;
                            }
                            else
                            {
                                range.markup = 0;
                                range.desconto = 0;
                                range.markupNet = 0;
                                range.descontoNet = 0;
                            }
                        }
                        else
                        {
                            if (StatusMeal.Equals(""))
                            {

                                range.markup = markupcliente;
                                range.desconto = descontocliente;
                                range.markupNet = 0;
                                range.descontoNet = 0;
                            }
                            else
                            {
                                range.markup = 0;
                                range.desconto = 0;
                                range.markupNet = 0;
                                range.descontoNet = 0;
                            }
                        }

                        range.FileTabelaId = IdTarifa;

                        rd.Salvar(range);

                        if (!range.Ranges_de.Equals("TC", StringComparison.OrdinalIgnoreCase))
                        {
                            ids.Add(range.Ranges_id);
                        }

                        if (StatusMeal.Equals(""))
                        {
                            AcertaRange(range.Ranges_id, IdTarifa, range.Flag);
                        }
                        else
                        {
                            AtualizaMeal(Convert.ToInt32(IdTarifa));
                        }

                    }



                }

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void SalvaRangesMealVazio(string StatusMeal, int IdMeal, DateTime dtFrom, DateTime dtTo, int IdMoeda, decimal markupcliente, decimal descontocliente, int IdSupplier, string valor, int IdTarifa)
        {
            try
            {

                RangeDal rd = new RangeDal();
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                CambioDAL cambDal = new CambioDAL();
                MealDAL mdal = new MealDAL();

                S_Mercado_Meal mealLast = mdal.ObterPorId(IdMeal);

                Ranges range = new Ranges();
                range.Ranges_de = txtBaseDeNew.Text;
                range.Ranges_ate = txtBaseAteNew.Text;
                range.Quotation_Id = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));
                range.Flag = "hotel";

                range.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                bool existe = rd.VerificaExisteRegOpt(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), Convert.ToInt32(ViewState["QuoteAtiva"]));

                //if (rd.ListarTodosGroup(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text))).Count == 0)
                if (!existe)
                {
                    range.Ordem = 1;
                }
                else
                {
                    range.Ordem = rd.ObterPorTarifaLast(IdTarifa).Ordem + 1;
                }

                decimal valorComCambio;
                decimal valorR = 0;

                TarifaDAL td = new TarifaDAL();

                if (StatusMeal.Equals(""))
                {
                    if (IdMoeda.ToString() != ddlMoeda.SelectedValue)
                    {
                        Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(IdMoeda), Convert.ToInt32(ddlMoeda.SelectedValue));

                        valorR = Convert.ToDecimal(valor);
                        valorComCambio = valorR * Convert.ToDecimal(camb.Cambio1);

                        range.Valor = valorComCambio;
                    }
                    else
                    {
                        range.Valor = Convert.ToDecimal(valor);
                    }
                }

                SupplierDAL sd = new SupplierDAL();
                MarkupPaisDAL mkd = new MarkupPaisDAL();

                Supplier spp = sd.ObterPorId(Convert.ToInt32(IdSupplier));

                if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                {
                    MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                    if (StatusMeal.Equals(""))
                    {
                        range.markup = mkp.Markup;
                        range.desconto = mkp.Desconto;
                        range.markupNet = markupcliente;
                        range.descontoNet = descontocliente;
                    }
                    else
                    {
                        range.markup = 0;
                        range.desconto = 0;
                        range.markupNet = 0;
                        range.descontoNet = 0;
                    }
                }
                else
                {
                    if (StatusMeal.Equals(""))
                    {

                        range.markup = markupcliente;
                        range.desconto = descontocliente;
                        range.markupNet = 0;
                        range.descontoNet = 0;
                    }
                    else
                    {
                        range.markup = 0;
                        range.desconto = 0;
                        range.markupNet = 0;
                        range.descontoNet = 0;
                    }
                }

                range.FileTabelaId = IdTarifa;

                rd.Salvar(range);

                if (StatusMeal.Equals(""))
                {
                    AcertaRange(range.Ranges_id, IdTarifa, range.Flag);
                }
                else
                {
                    AtualizaMeal(Convert.ToInt32(IdTarifa));
                }

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void PopulaNewQuote(int IdQuoteGrupo, int OptQuote)
        {
            try
            {
                FileCarrinhoDAL cd = new FileCarrinhoDAL();

                GridBasesTarifas.DataSource = cd.MontaCarrinhoNewFile(IdQuoteGrupo, OptQuote);
                GridBasesTarifas.DataBind();

                GridBases(GridBasesTarifas);

                //GeraTotalNewQuote();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void GridBases(GridView grid)
        {
            try
            {

                if (grid.Rows.Count == 0)
                {
                    return;
                }

                foreach (GridViewRow item in grid.Rows)
                {
                    //Label IdFileTarifas = (Label)item.FindControl("IdFileTarifas");
                    ImageButton imgFlights = (ImageButton)item.FindControl("imgFlights");
                    Label lblRoom = (Label)item.FindControl("lblRoom");
                    Label lblCategoria = (Label)item.FindControl("lblCategoria");
                    Label lblFlag = (Label)item.FindControl("lblFlag");
                    Label lblIdRetorna = (Label)item.FindControl("lblIdRetorna");
                    Label lblCidade = (Label)item.FindControl("lblCidade");
                    Label lblCidadeIata = (Label)item.FindControl("lblCidadeIata");
                    Label lblNomeSupplier = (Label)item.FindControl("lblNomeSupplier");
                    Label lblStatus = (Label)item.FindControl("lblStatus");
                    Label lblBulk = (Label)item.FindControl("lblBulk");
                    ImageButton imgBulk = (ImageButton)item.FindControl("imgBulk");
                    ImageButton imgStatus = (ImageButton)item.FindControl("imgStatus");

                    Label lblSubServico = (Label)item.FindControl("lblSubServico");
                    //ImageButton imgEditSubServico = (ImageButton)item.FindControl("imgEditSubServico");

                    CidadeDAL cdl = new CidadeDAL();

                    //if (lblSubServico.Text.Equals("true", StringComparison.OrdinalIgnoreCase))
                    //{
                    //    imgEditSubServico.Visible = true;
                    //}
                    //else
                    //{
                    //    imgEditSubServico.Visible = false;
                    //}

                    if (lblStatus.Text.Equals("OR"))
                    {
                        imgStatus.ImageUrl = "~/images/Icones/OnRequest.bmp";
                    }
                    else
                    {
                        imgStatus.ImageUrl = "~/images/Icones/Confirm.bmp";
                    }

                    if (lblBulk.Text.Equals("False") || lblBulk.Text.Equals(""))
                    {
                        imgBulk.ImageUrl = "~/images/minus-small.png";
                    }
                    else
                    {
                        imgBulk.ImageUrl = "~/images/valid.gif";
                    }

                    switch (lblFlag.Text)
                    {
                        case "hotel":
                            FileTarifasDAL ftd = new FileTarifasDAL();

                            File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));

                            Cidade chotel = cdl.ObterPorNomeSupplier(ft.S_nome);

                            if (ft.S_meal_nome == null)
                            {
                                lblNomeSupplier.Text = ft.S_nome;
                            }
                            else
                            {
                                lblNomeSupplier.Text = ft.S_nome + " - " + ft.S_meal_nome;
                            }

                            lblCidade.Text = chotel.CID_nome;
                            lblCidadeIata.Text = chotel.CID_cod_Iata;

                            if (ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text)).Flights_id == null)
                            {
                                imgFlights.ImageUrl = "~/images/Icones/flightsS.png";
                            }
                            else
                            {
                                imgFlights.ImageUrl = "~/images/Icones/flights.png";
                            }

                            break;

                        case "servico":
                            FileTransfersDAL fttd = new FileTransfersDAL();

                            File_Transfers ftra = fttd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));

                            lblNomeSupplier.Text = ftra.Transf_nome;

                            //Cidade cserv = cdl.ObterPorNomeServico(ftra.Transf_nome);
                            Cidade cserv = cdl.ObterPorId(Convert.ToInt32(ftra.Trf_CID_id));

                            lblCidade.Text = cserv.CID_nome;
                            lblCidadeIata.Text = cserv.CID_cod_Iata;

                            if (fttd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text)).Flights_id == null)
                            {
                                imgFlights.ImageUrl = "~/images/Icones/flightsS.png";
                            }
                            else
                            {
                                imgFlights.ImageUrl = "~/images/Icones/flights.png";
                            }

                            break;
                        case "extra":
                            FileServExtraDAL fses = new FileServExtraDAL();

                            File_ServExtra fsext = fses.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));

                            lblNomeSupplier.Text = fsext.File_ServExtra_nome;

                            Cidade cservextra = cdl.ObterPorNomeSupplier(fsext.S_nome);

                            lblCidade.Text = cservextra.CID_nome;
                            lblCidadeIata.Text = cservextra.CID_cod_Iata;

                            if (fses.ObterPorId(Convert.ToInt32(lblIdRetorna.Text)).Flights_id == null)
                            {
                                imgFlights.ImageUrl = "~/images/Icones/flightsS.png";
                            }
                            else
                            {
                                imgFlights.ImageUrl = "~/images/Icones/flights.png";
                            }

                            break;
                    }

                }

                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                int IdQuote = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));

                RangeDal rd = new RangeDal();

                int i = 8;
                int contador = 0;
                bool exists;
                List<int> ids = new List<int>();
                List<string> BasesAdicionadas = new List<string>();
                //bool jrange = false;
                //List<int> RangesID = new List<int>();

                bool flag = true;

                foreach (Ranges item in rd.ListarTodos(IdQuote, Convert.ToInt32(ViewState["QuoteAtiva"])))
                {
                    //int count = rd.ListarTodosGroup(IdQuote).Count;

                    if (!item.Ranges_de.Equals("TC"))
                    {
                        exists = BasesAdicionadas.Exists(element => element.Equals(item.Ranges_de));
                        flag = true;
                    }
                    else
                    {
                        exists = false;
                        //jrange = RangesID.Exists(e => e.Equals(item.RangeID));
                    }

                    if (flag && !exists)
                    {

                        GridBasesTarifas.Columns[i].Visible = true;
                        GridBasesTarifas.HeaderRow.Cells[i].Text = item.Ranges_de + "/" + item.Ranges_ate;

                        int[] arrayOf = ids.ToArray();
                        contador = arrayOf.Count();

                        foreach (GridViewRow item2 in grid.Rows)
                        {
                            Label lblIdRetorna = (Label)item2.FindControl("lblIdRetorna");
                            Label lblFlag = (Label)item2.FindControl("lblFlag");
                            Label lblNomeStatus = (Label)item2.FindControl("lblNomeStatus");

                            BasesAdicionadas.Add(item.Ranges_de);

                            Ranges r;

                            if (item.Ranges_de.Equals("TC"))
                            {
                                r = rd.ObterPorTarifa(IdQuote, Convert.ToInt32(lblIdRetorna.Text), item.Ranges_de, item.Ranges_ate, lblFlag.Text, arrayOf[0], Convert.ToInt32(ViewState["QuoteAtiva"]));

                                int numToRemove = arrayOf[0];
                                arrayOf = arrayOf.Where(val => val != numToRemove).ToArray();

                                if (arrayOf.Count() == 0)
                                {
                                    ids.Clear();
                                    flag = false;
                                }
                            }
                            else
                            {
                                r = rd.ObterPorTarifaOptQuote(IdQuote, Convert.ToInt32(lblIdRetorna.Text), item.Ranges_de, item.Ranges_ate, lblFlag.Text, Convert.ToInt32(ViewState["QuoteAtiva"]));
                                ids.Add(r.Ranges_id);
                            }

                            switch (i)
                            {
                                case 8:

                                    LinkButton lnkValorTotalHotel8 = (LinkButton)item2.FindControl("lnkValorTotalHotel8");

                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel8.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel8.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel8.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 9:

                                    LinkButton lnkValorTotalHotel9 = (LinkButton)item2.FindControl("lnkValorTotalHotel9");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel9.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel9.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel9.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 10:

                                    LinkButton lnkValorTotalHotel10 = (LinkButton)item2.FindControl("lnkValorTotalHotel10");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel10.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel10.Text = "O/R";
                                    //}


                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel10.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 11:

                                    LinkButton lnkValorTotalHotel11 = (LinkButton)item2.FindControl("lnkValorTotalHotel11");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel11.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel11.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel11.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 12:

                                    LinkButton lnkValorTotalHotel12 = (LinkButton)item2.FindControl("lnkValorTotalHotel12");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel12.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel12.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel12.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 13:

                                    LinkButton lnkValorTotalHotel13 = (LinkButton)item2.FindControl("lnkValorTotalHotel13");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel13.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel13.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel13.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 14:

                                    LinkButton lnkValorTotalHotel14 = (LinkButton)item2.FindControl("lnkValorTotalHotel14");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel14.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel14.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel14.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 15:

                                    LinkButton lnkValorTotalHotel15 = (LinkButton)item2.FindControl("lnkValorTotalHotel15");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel15.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel15.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel15.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 16:

                                    LinkButton lnkValorTotalHotel16 = (LinkButton)item2.FindControl("lnkValorTotalHotel16");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel16.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel16.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel16.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 17:

                                    LinkButton lnkValorTotalHotel17 = (LinkButton)item2.FindControl("lnkValorTotalHotel17");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel17.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel17.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel17.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 18:

                                    LinkButton lnkValorTotalHotel18 = (LinkButton)item2.FindControl("lnkValorTotalHotel18");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel18.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel18.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel18.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 19:

                                    LinkButton lnkValorTotalHotel19 = (LinkButton)item2.FindControl("lnkValorTotalHotel19");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel19.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel19.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel19.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 20:

                                    LinkButton lnkValorTotalHotel20 = (LinkButton)item2.FindControl("lnkValorTotalHotel20");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel20.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel20.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel20.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 21:

                                    LinkButton lnkValorTotalHotel21 = (LinkButton)item2.FindControl("lnkValorTotalHotel21");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel21.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel21.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel21.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 22:

                                    LinkButton lnkValorTotalHotel22 = (LinkButton)item2.FindControl("lnkValorTotalHotel22");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel22.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel22.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel22.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 23:

                                    LinkButton lnkValorTotalHotel23 = (LinkButton)item2.FindControl("lnkValorTotalHotel23");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel23.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel23.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel23.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 24:

                                    LinkButton lnkValorTotalHotel24 = (LinkButton)item2.FindControl("lnkValorTotalHotel24");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel24.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel24.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel24.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 25:

                                    LinkButton lnkValorTotalHotel25 = (LinkButton)item2.FindControl("lnkValorTotalHotel25");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel25.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel25.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel25.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 26:

                                    LinkButton lnkValorTotalHotel26 = (LinkButton)item2.FindControl("lnkValorTotalHotel26");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel26.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel26.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel26.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 27:

                                    LinkButton lnkValorTotalHotel27 = (LinkButton)item2.FindControl("lnkValorTotalHotel27");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel27.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel27.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel27.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 28:

                                    LinkButton lnkValorTotalHotel28 = (LinkButton)item2.FindControl("lnkValorTotalHotel28");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel28.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel28.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel28.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 29:

                                    LinkButton lnkValorTotalHotel29 = (LinkButton)item2.FindControl("lnkValorTotalHotel29");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel29.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel29.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel29.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 31:

                                    LinkButton lnkValorTotalHotel31 = (LinkButton)item2.FindControl("lnkValorTotalHotel31");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel31.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel31.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel31.Text = ft.S_meal_status;
                                    }

                                    break;

                                case 32:

                                    LinkButton lnkValorTotalHotel32 = (LinkButton)item2.FindControl("lnkValorTotalHotel32");
                                    //if (r.ValorTotal != 0)
                                    //{
                                    lnkValorTotalHotel32.Text = r.ValorTotal.ToString();
                                    //}
                                    //else
                                    //{
                                    //    lnkValorTotalHotel32.Text = "O/R";
                                    //}

                                    if (!lblNomeStatus.Text.Equals(""))
                                    {
                                        FileTarifasDAL ftd = new FileTarifasDAL();
                                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                        lnkValorTotalHotel32.Text = ft.S_meal_status;
                                    }

                                    break;
                            }
                        }

                        i = i + 1;


                    }

                    ViewState["QtdDeColunas"] = i - 8;
                }
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        private int[] descendSort(int[] array)
        {
            int[] tempArray = new int[array.Length];
            for (int i = array.Length - 1; i <= 0; --i)
            {
                for (int j = 0; j < array.Length - 1; ++i)
                {
                    tempArray[j] = array[i];
                }
            }
            return tempArray;
        }

        protected void txtAutoCidadeHotel_TextChanged(object sender, EventArgs e)
        {
            try
            {
                ViewState["IdCidadeHotel"] = new CidadeDAL().ObterPorNome(txtAutoCidadeHotel.Text).CID_id;

                PopularDropHoteisFiltro();
                lblPaxsHoteis.Visible = false;
                lblEstacaoHoteis.Visible = false;
                ddlPaxsHoteis.Visible = false;
                ddlEstacoesHoteis.Visible = false;
                DataListHoteis.DataBind();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void txtAutoCidadeTransfer_TextChanged(object sender, EventArgs e)
        {
            try
            {
                ViewState["IdCidadeTransfer"] = new CidadeDAL().ObterPorNome(txtAutoCidadeTransfer.Text).CID_id;

                PopulaDropSuppliersTransPorCidade();

                DataListTransfersSubServicos.DataBind();
                DataListTransfers.DataBind();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void txtAutoCidadeTours_TextChanged(object sender, EventArgs e)
        {
            try
            {
                ViewState["IdCidadeTour"] = new CidadeDAL().ObterPorNome(txtAutoCidadeTours.Text).CID_id;

                PopulaDropSuppliersToursPorCidade();

                DataListToursSubServicos.DataBind();
                DataListTours.DataBind();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnAddBaseNew_Click(object sender, EventArgs e)
        {
            try
            {

                FileTarifasDAL ftd = new FileTarifasDAL();
                FileTransfersDAL ftrasd = new FileTransfersDAL();
                FileServExtraDAL fserv = new FileServExtraDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                RangeDal rd = new RangeDal();

                int IdQuot = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));

                foreach (Ranges item in rd.ListarTodos(IdQuot))
                {
                    Ranges novo = new Ranges();

                    novo.DAY = null;
                    novo.Ranges_id = item.Ranges_id;

                    rd.AtualizarDAY(novo);
                }

                ClienteMarkupDAL climark = new ClienteMarkupDAL();

                decimal markupcliente = 0, descontocliente = 0;

                //decimal markupcliente = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_hotel);
                //decimal descontocliente = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_descontoHotel);

                int i = 8;

                foreach (GridViewRow item in GridBasesTarifas.Rows)
                {
                    Label IdFileTarifas = (Label)item.FindControl("IdFileTarifas");
                    Label lblRangeId = (Label)item.FindControl("lblRangeId");
                    Label lblFlag = (Label)item.FindControl("lblFlag");

                    if (txtBaseDeNew.Text.Equals("TC", StringComparison.OrdinalIgnoreCase))
                    {

                        Ranges rnew = new Ranges();
                        rnew.Ranges_de = txtBaseDeNew.Text;
                        rnew.Ranges_ate = txtBaseAteNew.Text;
                        rnew.Quotation_Id = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));
                        rnew.Flag = lblFlag.Text;

                        rnew.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                        switch (lblFlag.Text)
                        {
                            case "hotel":
                                File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(IdFileTarifas.Text));
                                rnew.FileTabelaId = ft.File_Tarifas_id;
                                break;
                            case "servico":
                                File_Transfers ftr = ftrasd.ObterPorId(Convert.ToInt32(IdFileTarifas.Text));
                                rnew.FileTabelaId = ftr.File_Transf_id;
                                break;
                            case "extra":
                                File_ServExtra fser = fserv.ObterPorId(Convert.ToInt32(IdFileTarifas.Text));
                                rnew.FileTabelaId = fser.File_ServExtra_id;
                                break;
                        }

                        rnew.markup = 0;
                        rnew.desconto = 0;
                        rnew.markupNet = 0;
                        rnew.descontoNet = 0;
                        rnew.VendaNet = 0;
                        rnew.Valor = 0;
                        rnew.Venda = 0;
                        rnew.ValorTotal = 0;

                        rd.Salvar(rnew);

                    }
                    else
                    {

                        if (lblFlag.Text.Equals("hotel"))
                        {
                            File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(IdFileTarifas.Text));
                            Ranges r = rd.ObterPorTarifaLast(Convert.ToInt32(IdFileTarifas.Text), "hotel");

                            Ranges rnew = new Ranges();
                            rnew.Ranges_de = txtBaseDeNew.Text;
                            rnew.Ranges_ate = txtBaseAteNew.Text;

                            rnew.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                            rnew.Ordem = r.Ordem + 1;

                            rnew.Quotation_Id = r.Quotation_Id;
                            rnew.Flag = r.Flag;
                            rnew.FileTabelaId = r.FileTabelaId;
                            rnew.markup = r.markup;
                            rnew.desconto = r.desconto;
                            rnew.markupNet = r.markupNet;
                            rnew.descontoNet = r.descontoNet;
                            rnew.VendaNet = r.VendaNet;
                            rnew.Valor = r.Valor;
                            rnew.Venda = r.Venda;
                            rnew.ValorTotal = r.ValorTotal;

                            rd.Salvar(rnew);
                        }
                        else if (lblFlag.Text.Equals("servico"))
                        {

                            File_Transfers ft = ftrasd.ObterPorId(Convert.ToInt32(IdFileTarifas.Text));

                            MoedaDAL mod = new MoedaDAL();
                            //Moeda m = mod.RetornaIdPorTransfer(ft.Transf_nome);

                            string[] titulo = GridBasesTarifas.HeaderRow.Cells[i].Text.ToString().Split('/');

                            Ranges r = rd.ObterPorTarifa(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), Convert.ToInt32(IdFileTarifas.Text), titulo[0], titulo[1], lblFlag.Text);
                                                        
                            List<SubServicosFile> sublista = new SubServicosFileDAL().ListarTodosRange(r.Ranges_id, 0);

                            Moeda m;

                            if (Convert.ToBoolean(ft.SubServico))
                            {
                                 m = mod.RetornaIdPorTransfer1(ft.Transf_nome);
                            }
                            else
                            {
                                 m = mod.RetornaIdPorTransfer(ft.Transf_nome);
                            }


                            ViewState.Add("sublista", sublista);

                            decimal valor = 0;

                            ViewState["DatasAddBaseFrom"] = Convert.ToDateTime(ft.Data_From);
                            ViewState["DatasAddBaseTo"] = Convert.ToDateTime(ft.Data_To);

                            MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToDateTime(ft.Data_From));
                            if (mkfile != null)
                            {
                                markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                                descontocliente = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                            }
                            else
                            {
                                MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(Convert.ToDateTime(ft.Data_From));

                                if (mgfile != null)
                                {
                                    markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                                    descontocliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                                }
                                else
                                {
                                    MostrarMsg("Não existe Markup cadastrado.");
                                    return;
                                }
                            }

                            SalvaRangesServicosVazio("add", Convert.ToBoolean(ft.SubServico), Convert.ToInt32(ft.S_id),
                                                     markupcliente, descontocliente, ft.Transf_nome, Convert.ToInt32(m.Moeda_id),
                                                     Convert.ToInt32(ft.File_Transf_id));
                        }
                        else
                        {
                            File_ServExtra fs = fserv.ObterPorId(Convert.ToInt32(IdFileTarifas.Text));

                            Ranges r = rd.ObterPorTarifaLast(Convert.ToInt32(IdFileTarifas.Text));

                            Ranges rnew = new Ranges();
                            rnew.Ranges_de = txtBaseDeNew.Text;
                            rnew.Ranges_ate = txtBaseAteNew.Text;
                            rnew.Quotation_Id = r.Quotation_Id;
                            rnew.Flag = "extra";
                            rnew.FileTabelaId = fs.File_ServExtra_id;

                            rnew.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                            if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                            {
                                SupplierDAL sd = new SupplierDAL();
                                MarkupPaisDAL mkd = new MarkupPaisDAL();

                                Supplier spp = sd.ObterPorId(Convert.ToInt32(fs.S_id));
                                MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                                rnew.markup = mkp.Markup;
                                rnew.desconto = mkp.Desconto;
                                rnew.markupNet = markupcliente;
                                rnew.descontoNet = descontocliente;
                            }
                            else
                            {

                                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToDateTime(fs.Data_From));
                                if (mkfile != null)
                                {
                                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                                    descontocliente = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                                }
                                else
                                {
                                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(Convert.ToDateTime(fs.Data_From));

                                    if (mgfile != null)
                                    {
                                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                                        descontocliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                                    }
                                    else
                                    {
                                        MostrarMsg("Não existe Markup cadastrado.");
                                        return;
                                    }
                                }

                                rnew.markup = markupcliente;
                                rnew.desconto = descontocliente;
                                rnew.markupNet = 0;
                                rnew.descontoNet = 0;
                            }

                            rnew.VendaNet = 0;
                            rnew.Valor = 0;
                            rnew.Venda = 0;
                            rnew.ValorTotal = 0;

                            rd.Salvar(rnew);
                        }
                    }



                }


                PopulaNewQuote(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToInt32(ViewState["QuoteAtiva"]));

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void AcertaRange(int IdRange, int IdRetorna, string flag)
        {
            try
            {
                RangeDal rd = new RangeDal();
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileTransfersDAL ftrsd = new FileTransfersDAL();

                Ranges r = rd.ObterPorId(IdRange);

                double venda = 0;

                if (Convert.ToDecimal(r.markup) < 1)
                {
                    venda = (Convert.ToDouble(r.Valor) / Convert.ToDouble(r.markup));
                }
                else
                {
                    venda = (Convert.ToDouble(r.Valor) * Convert.ToDouble(r.markup) / 100) + Convert.ToDouble(r.Valor);
                }


                if (!double.IsNaN(venda))
                {
                    ArredondaDAL arrd = new ArredondaDAL();
                    string[] pars = Convert.ToDecimal(venda).ToString().Split(',');
                    decimal valorArr = 0;

                    if (pars.Count() > 1)
                    {
                        Arredonda arr;

                        if (pars[1].Length == 1)
                        {
                            string val = pars[1] + 0;
                            arr = arrd.ObterArr(Convert.ToInt32(val.Substring(0, 2)));
                        }
                        else
                        {
                            arr = arrd.ObterArr(Convert.ToInt32(pars[1].Substring(0, 2)));
                        }

                        if (arr.Arredonda_recebe < 1)
                        {
                            valorArr = Convert.ToDecimal(pars[0]) + Convert.ToDecimal(arr.Arredonda_recebe);
                            venda = Convert.ToDouble(valorArr);
                        }
                        else
                        {
                            valorArr = Convert.ToDecimal(pars[0]) + Convert.ToDecimal(arr.Arredonda_recebe);
                            venda = Convert.ToDouble(valorArr);
                        }
                    }
                }


                if (flag.Equals("hotel"))
                {
                    File_Tarifas ft = ftd.ObterPorId(IdRetorna);

                    double addDesconto = venda - (venda * Convert.ToDouble(r.desconto) / 100);

                    double addNrNoites = Convert.ToDouble(ft.NumNoites) * addDesconto;

                    double addMarkupNet = (Convert.ToDouble(addNrNoites) * Convert.ToDouble(r.markupNet) / 100) + Convert.ToDouble(addNrNoites);

                    double addDescontoNet = addMarkupNet - (addMarkupNet * Convert.ToDouble(r.descontoNet) / 100);

                    //double multNet = Convert.ToDouble(ft.Paying_Pax) * addDescontoNet;
                    double multNet = addDescontoNet;

                    Ranges rnew = new Ranges();
                    rnew.Ranges_id = IdRange;
                    rnew.VendaNet = Convert.ToDecimal(addNrNoites);
                    rnew.Venda = Convert.ToDecimal(addDescontoNet);
                    rnew.ValorTotal = Convert.ToDecimal(multNet);
                    rnew.Valor = Convert.ToDecimal(r.Valor);
                    rnew.markup = r.markup;
                    rnew.markupNet = r.markupNet;
                    rnew.desconto = r.desconto;
                    rnew.descontoNet = r.descontoNet;

                    rd.AtualizarValores(rnew);

                }
                else if (flag.Equals("servico"))
                {

                    File_Transfers ft = ftrsd.ObterPorId(IdRetorna);

                    if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                    {
                        double addDesconto = venda - (venda * Convert.ToDouble(r.desconto) / 100);

                        double mult = Convert.ToDouble(ft.Paying_Pax) * addDesconto;

                        //txtVendaNet.Text = addDesconto.ToString("N");
                        double addMarkupNet = (Convert.ToDouble(addDesconto) * Convert.ToDouble(r.markupNet) / 100) + Convert.ToDouble(addDesconto);

                        double addDescontoNet = addMarkupNet - (addMarkupNet * Convert.ToDouble(r.descontoNet) / 100);

                        //double multNet = Convert.ToDouble(ft.Paying_Pax) * addDescontoNet;

                        double multNet = addDescontoNet;

                        //txtVenda.Text = addDescontoNet.ToString("N");

                        //lblValorTotalTarifas.Text = multNet.ToString("N");                        

                        Ranges rnew = new Ranges();
                        rnew.Ranges_id = IdRange;
                        rnew.VendaNet = Convert.ToDecimal(addDesconto);
                        rnew.Venda = Convert.ToDecimal(addDescontoNet);
                        rnew.ValorTotal = Convert.ToDecimal(multNet);
                        rnew.Valor = Convert.ToDecimal(r.Valor);
                        rnew.markup = r.markup;
                        rnew.markupNet = r.markupNet;
                        rnew.desconto = r.desconto;
                        rnew.descontoNet = r.descontoNet;

                        rd.AtualizarValores(rnew);
                    }
                    else
                    {
                        double addDesconto = venda - (venda * Convert.ToDouble(r.desconto) / 100);

                        //double mult = Convert.ToDouble(ft.Paying_Pax) * addDesconto;

                        double mult = addDesconto;

                        Ranges rTC = rd.ObterPorIdID(IdRange);

                        Ranges rnew = new Ranges();

                        if (rTC == null) rnew.Ranges_id = IdRange; else rnew.Ranges_id = rTC.Ranges_id;

                        rnew.VendaNet = Convert.ToDecimal(addDesconto);
                        rnew.Venda = Convert.ToDecimal(addDesconto);
                        rnew.ValorTotal = Convert.ToDecimal(mult);
                        rnew.Valor = Convert.ToDecimal(r.Valor);
                        rnew.markup = r.markup;
                        rnew.markupNet = r.markupNet;
                        rnew.desconto = r.desconto;
                        rnew.descontoNet = r.descontoNet;

                        rd.AtualizarValores(rnew);

                        //ft.markupNet = 0;
                        //ft.descontoNet = 0;
                    }

                }


            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void AcertaRangeDirFile(int IdRetorna, string flag)
        {
            try
            {
                QuoteTarifasDAL ftd = new QuoteTarifasDAL();
                QuoteTransDAL ftrsd = new QuoteTransDAL();
                QuoteModelRange r = new QuoteModelRange();

                switch (flag)
                {
                    case "hotel":
                        Quote_Tarifas qtar = ftd.ObterPorId(IdRetorna);

                        r.valor = (decimal)qtar.S_merc_tarif_valor;
                        r.markup = (decimal)qtar.markup;
                        r.desconto = (decimal)qtar.desconto;
                        r.markupNet = (decimal)qtar.markupNet;
                        r.descontoNet = (decimal)qtar.markupNet;
                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        {
                            r.vendaNet = (decimal)qtar.S_merc_tarif_vendaNet;
                        }
                        break;
                    case "servico":
                        Quote_Transf qtrs = ftrsd.ObterPorId(IdRetorna);

                        r.valor = (decimal)qtrs.Transf_valor;
                        r.markup = (decimal)qtrs.markup;
                        r.desconto = (decimal)qtrs.desconto;
                        r.markupNet = (decimal)qtrs.markupNet;
                        r.descontoNet = (decimal)qtrs.markupNet;
                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        {
                            r.vendaNet = (decimal)qtrs.S_merc_tarif_vendaNet;
                        }
                        break;
                }

                //Ranges r = rd.ObterPorId(IdRange);

                double venda = 0;

                if (Convert.ToDecimal(r.markup) < 1)
                {
                    venda = (Convert.ToDouble(r.valor) / Convert.ToDouble(r.markup));
                }
                else
                {
                    venda = (Convert.ToDouble(r.valor) * Convert.ToDouble(r.markup) / 100) + Convert.ToDouble(r.valor);
                }

                ArredondaDAL arrd = new ArredondaDAL();

                string[] pars = Convert.ToDecimal(venda).ToString().Split(',');
                decimal valorArr = 0;

                if (pars.Count() > 1)
                {
                    Arredonda arr;

                    if (pars[1].Length == 1)
                    {
                        string val = pars[1] + 0;
                        arr = arrd.ObterArr(Convert.ToInt32(val.Substring(0, 2)));
                    }
                    else
                    {
                        arr = arrd.ObterArr(Convert.ToInt32(pars[1].Substring(0, 2)));
                    }

                    if (arr.Arredonda_recebe < 1)
                    {
                        valorArr = Convert.ToDecimal(pars[0]) + Convert.ToDecimal(arr.Arredonda_recebe);
                        venda = Convert.ToDouble(valorArr);
                    }
                    else
                    {
                        valorArr = Convert.ToDecimal(pars[0]) + Convert.ToDecimal(arr.Arredonda_recebe);
                        venda = Convert.ToDouble(valorArr);
                    }
                }


                if (flag.Equals("hotel"))
                {
                    Quote_Tarifas ft = ftd.ObterPorId(IdRetorna);

                    double addDesconto = venda - (venda * Convert.ToDouble(r.desconto) / 100);

                    double addNrNoites = Convert.ToDouble(ft.NumNoites) * addDesconto;

                    double addMarkupNet = (Convert.ToDouble(addNrNoites) * Convert.ToDouble(r.markupNet) / 100) + Convert.ToDouble(addNrNoites);

                    double addDescontoNet = addMarkupNet - (addMarkupNet * Convert.ToDouble(r.descontoNet) / 100);

                    double multNet = addDescontoNet;

                    Quote_Tarifas qtt = new Quote_Tarifas();
                    qtt.S_merc_tarif_vendaNet = (decimal)addNrNoites;
                    qtt.S_merc_tarif_venda = (decimal)addDescontoNet;
                    qtt.S_merc_tarif_total = (decimal)multNet;
                    qtt.S_merc_tarif_valor = (decimal)r.valor;
                    qtt.markup = r.markup;
                    qtt.markupNet = r.markupNet;
                    qtt.desconto = r.desconto;
                    qtt.descontoNet = r.descontoNet;
                    qtt.Quote_Tarifas_id = ft.Quote_Tarifas_id;

                    ftd.AtualizarValores(qtt);

                }
                else if (flag.Equals("servico"))
                {

                    Quote_Transf ft = ftrsd.ObterPorId(IdRetorna);

                    if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                    {
                        double addDesconto = venda - (venda * Convert.ToDouble(r.desconto) / 100);

                        double mult = Convert.ToDouble(ft.Paying_Pax) * addDesconto;

                        double addMarkupNet = (Convert.ToDouble(r.vendaNet) * Convert.ToDouble(r.markupNet) / 100) + Convert.ToDouble(r.markupNet);

                        double addDescontoNet = addMarkupNet - (addMarkupNet * Convert.ToDouble(r.descontoNet) / 100);

                        double multNet = addDescontoNet;

                        Quote_Transf qtt = new Quote_Transf();
                        qtt.S_merc_tarif_vendaNet = (decimal)addDesconto;
                        qtt.Transf_venda = (decimal)addDescontoNet;
                        qtt.Transf_vendaNet = (decimal)addDescontoNet;
                        qtt.Transf_total = (decimal)multNet;
                        qtt.Transf_valor = (decimal)r.valor;
                        qtt.markup = r.markup;
                        qtt.markupNet = r.markupNet;
                        qtt.desconto = r.desconto;
                        qtt.descontoNet = r.descontoNet;
                        qtt.Quote_Transf_id = ft.Quote_Transf_id;

                        ftrsd.AtualizarValores(qtt);

                    }
                    else
                    {
                        double addDesconto = venda - (venda * Convert.ToDouble(r.desconto) / 100);
                        double mult = addDesconto;

                        Quote_Transf qtt = new Quote_Transf();
                        qtt.S_merc_tarif_vendaNet = (decimal)addDesconto;
                        qtt.Transf_venda = (decimal)addDesconto;
                        qtt.Transf_vendaNet = (decimal)addDesconto;
                        qtt.Transf_total = (decimal)mult;
                        qtt.Transf_valor = (decimal)r.valor;
                        qtt.markup = r.markup;
                        qtt.markupNet = r.markupNet;
                        qtt.desconto = r.desconto;
                        qtt.descontoNet = r.descontoNet;
                        qtt.Quote_Transf_id = ft.Quote_Transf_id;

                        ftrsd.AtualizarValores(qtt);
                    }

                }


            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void AcertaValores(int IdFtarifas)
        {
            try
            {
                FileTarifasDAL ftd = new FileTarifasDAL();

                File_Tarifas ft = ftd.ObterPorId(IdFtarifas);

                double venda = 0;


                if (Convert.ToDecimal(ft.markup) < 1)
                {
                    venda = (Convert.ToDouble(ft.S_merc_tarif_valor) / Convert.ToDouble(ft.markup));
                }
                else
                {
                    venda = (Convert.ToDouble(ft.S_merc_tarif_valor) * Convert.ToDouble(ft.markup) / 100) + Convert.ToDouble(ft.S_merc_tarif_valor);
                }

                ArredondaDAL arrd = new ArredondaDAL();

                string[] pars = Convert.ToDecimal(venda).ToString().Split(',');
                decimal valorArr = 0;

                if (pars.Count() > 1)
                {
                    Arredonda arr;

                    if (pars[1].Length == 1)
                    {
                        string val = pars[1] + 0;
                        arr = arrd.ObterArr(Convert.ToInt32(val.Substring(0, 2)));
                    }
                    else
                    {
                        arr = arrd.ObterArr(Convert.ToInt32(pars[1].Substring(0, 2)));
                    }

                    if (arr.Arredonda_recebe < 1)
                    {
                        valorArr = Convert.ToDecimal(pars[0]) + Convert.ToDecimal(arr.Arredonda_recebe);
                        venda = Convert.ToDouble(valorArr);
                    }
                    else
                    {
                        valorArr = Convert.ToDecimal(pars[0]) + Convert.ToDecimal(arr.Arredonda_recebe);
                        venda = Convert.ToDouble(valorArr);
                    }
                }



                double addDesconto = venda - (venda * Convert.ToDouble(ft.desconto) / 100);

                double addNrNoites = Convert.ToDouble(ft.NumNoites) * addDesconto;

                //txtVendaNet.Text = addNrNoites.ToString("N");

                double addMarkupNet = (Convert.ToDouble(addNrNoites) * Convert.ToDouble(ft.markupNet) / 100) + Convert.ToDouble(addNrNoites);

                double addDescontoNet = addMarkupNet - (addMarkupNet * Convert.ToDouble(ft.descontoNet) / 100);

                double multNet = Convert.ToDouble(ft.Paying_Pax) * addDescontoNet;

                //txtVenda.Text = addDescontoNet.ToString("N");

                //lblValorTotalTarifas.Text = multNet.ToString("N");

                File_Tarifas ftnew = new File_Tarifas();

                ftnew.File_Tarifas_id = ft.File_Tarifas_id;
                ftnew.S_merc_tarif_vendaNet = Convert.ToDecimal(addNrNoites);
                ftnew.S_merc_tarif_venda = Convert.ToDecimal(addDescontoNet);
                ftnew.S_merc_tarif_total = Convert.ToDecimal(multNet);
                ftnew.S_merc_tarif_valor = Convert.ToDecimal(ft.S_merc_tarif_valor);
                ftnew.markup = ft.markup; //Convert.ToDecimal(txtMarkup.Text);
                ftnew.markupNet = ft.markupNet; //Convert.ToDecimal(txtMarkupNet.Text);
                ftnew.desconto = ft.desconto; //Convert.ToDecimal(txtDesconto.Text);
                ftnew.descontoNet = ft.descontoNet; //Convert.ToDecimal(txtDescontoNet.Text);
                ftnew.Qtd_Tarifas = ft.Qtd_Tarifas; //Convert.ToInt32(txtQtdTarifas.Text);

                ftd.Atualizar(ftnew);

                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                VerificaRanges(fcd.RetornaQuote(Convert.ToInt32(ft.File_id)));
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void imgAtualizaTarifas_Click(object sender, ImageClickEventArgs e)
        {
            if (Convert.ToInt32(ViewState["TarifaFile"]) == 0)
            {
                AcertaValoresGrid(Convert.ToInt32(ViewState["IdFTarifasBases"]), sender, e);
            }
            else
            {
                AcertaValoresGridNewFile(Convert.ToInt32(ViewState["IdFTarifasBasesNewFile"]), sender, e);
            }
        }

        protected void imgAtualizaTarifasVenda_Click(object sender, ImageClickEventArgs e)
        {
            if (Convert.ToInt32(ViewState["TarifaFile"]) == 0)
            {
                AcertaValoresGridVenda(Convert.ToInt32(ViewState["IdFTarifasBases"]), sender, e);
            }
            else
            {
                AcertaValoresGridNewFileVenda(Convert.ToInt32(ViewState["IdFTarifasBasesNewFile"]), sender, e);
            }
        }

        protected void AcertaValoresGrid(int IdFtarifas, object sender, EventArgs e)
        {
            try
            {

                FileTarifasDAL ftd = new FileTarifasDAL();
                FileTransfersDAL ftrd = new FileTransfersDAL();
                FileServExtraDAL fssd = new FileServExtraDAL();

                string[] pars2 = ViewState["FlagTarifaClicada"].ToString().Split(',');
                int col = Convert.ToInt32(pars2[1]);

                int numNoites = 1;

                if (pars2[0].ToString().Equals("hotel"))
                {
                    File_Tarifas ft = ftd.ObterPorId(IdFtarifas);
                    numNoites = Convert.ToInt32(ft.NumNoites);
                }


                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                double venda = 0;


                if (Convert.ToDecimal(txtMarkupTarifas.Text) < 1)
                {
                    venda = (Convert.ToDouble(txtNetNetTarifas.Text) / Convert.ToDouble(txtMarkupTarifas.Text));
                }
                else
                {
                    venda = (Convert.ToDouble(txtNetNetTarifas.Text) * Convert.ToDouble(txtMarkupTarifas.Text) / 100) + Convert.ToDouble(txtNetNetTarifas.Text);
                }

                ArredondaDAL arrd = new ArredondaDAL();

                string[] pars = Convert.ToDecimal(venda).ToString().Split(',');
                decimal valorArr = 0;

                if (pars.Count() > 1)
                {
                    Arredonda arr;

                    if (pars[1].Length == 1)
                    {
                        string val = pars[1] + 0;
                        arr = arrd.ObterArr(Convert.ToInt32(val.Substring(0, 2)));
                    }
                    else
                    {
                        arr = arrd.ObterArr(Convert.ToInt32(pars[1].Substring(0, 2)));
                    }

                    if (arr.Arredonda_recebe < 1)
                    {
                        valorArr = Convert.ToDecimal(pars[0]) + Convert.ToDecimal(arr.Arredonda_recebe);
                        venda = Convert.ToDouble(valorArr);
                    }
                    else
                    {
                        valorArr = Convert.ToDecimal(pars[0]) + Convert.ToDecimal(arr.Arredonda_recebe);
                        venda = Convert.ToDouble(valorArr);
                    }
                }

                double addDesconto = venda - (venda * Convert.ToDouble(txtDescontoTarifas.Text) / 100);

                double addNrNoites = Convert.ToDouble(numNoites) * addDesconto;

                txtVendaTarifas.Text = addNrNoites.ToString("N");

                double addMarkupNet = (Convert.ToDouble(addNrNoites) * Convert.ToDouble(txtMarkupNetTarifas.Text) / 100) + Convert.ToDouble(addNrNoites);

                double addDescontoNet = addMarkupNet - (addMarkupNet * Convert.ToDouble(txtDescontoNetTarifas.Text) / 100);

                //double multNet = Convert.ToDouble(txtPaxsTarifas.Text) * addDescontoNet;
                double multNet = addDescontoNet;

                txtNetTarifas.Text = addDescontoNet.ToString("N");

                lbltotalTarifas.Text = multNet.ToString("N");

                RangeDal rg = new RangeDal();

                string[] titulo = GridBasesTarifas.HeaderRow.Cells[col].Text.ToString().Split('/');

                Ranges r = new Ranges();

                if (titulo[0].Equals("TC"))
                {
                    string[] titulo2 = GridBasesTarifas.HeaderRow.Cells[col - 1].Text.ToString().Split('/');
                    Ranges er = rg.ObterPorTarifa(IdFtarifas, titulo2[0], titulo2[1], fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), Convert.ToInt32(ViewState["QuoteAtiva"]), pars2[0].ToString());
                    r = rg.ObterPorIdID(er.Ranges_id);
                }
                else
                {
                    r = rg.ObterPorTarifa(IdFtarifas, titulo[0], titulo[1], fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), Convert.ToInt32(ViewState["QuoteAtiva"]), pars2[0].ToString());
                }

                switch (pars2[0].ToString())
                {
                    case "hotel":

                        //Ranges r = rg.ObterPorTarifa(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), IdFtarifas, titulo[0], titulo[1], pars2[0].ToString());

                        File_Tarifas ft = ftd.ObterPorId(IdFtarifas);

                        File_Tarifas ftnew = new File_Tarifas();
                        Ranges rnew = new Ranges();

                        rnew.VendaNet = Convert.ToDecimal(addNrNoites);
                        rnew.Venda = Convert.ToDecimal(addDescontoNet);
                        rnew.ValorTotal = Convert.ToDecimal(multNet);
                        rnew.Valor = Convert.ToDecimal(txtNetNetTarifas.Text);
                        rnew.markup = Convert.ToDecimal(txtMarkupTarifas.Text);
                        rnew.markupNet = Convert.ToDecimal(txtMarkupNetTarifas.Text);
                        rnew.desconto = Convert.ToDecimal(txtDescontoTarifas.Text);
                        rnew.descontoNet = Convert.ToDecimal(txtDescontoNetTarifas.Text);
                        rnew.Ranges_id = r.Ranges_id;

                        rg.AtualizarValores(rnew);

                        ftnew.Qtd_Tarifas = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftnew.Paxs = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftnew.Paying_Pax = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftnew.Supp_Paying_Pax = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftnew.File_Tarifas_id = ft.File_Tarifas_id;

                        ftd.AtualizarNew(ftnew);

                        PopulaNewQuote(fcd.RetornaQuote(Convert.ToInt32(ft.File_id)), Convert.ToInt32(ViewState["QuoteAtiva"]));

                        //VerificaRanges(fcd.RetornaQuote(Convert.ToInt32(ft.File_id)));

                        break;

                    case "servico":

                        //Ranges rr = rg.ObterPorTarifa(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), IdFtarifas, titulo[0], titulo[1], pars2[0].ToString());

                        File_Transfers ftr = ftrd.ObterPorId(IdFtarifas);

                        File_Transfers ftrnew = new File_Transfers();
                        Ranges rrnew = new Ranges();

                        rrnew.VendaNet = Convert.ToDecimal(addNrNoites);
                        rrnew.Venda = Convert.ToDecimal(addDescontoNet);
                        rrnew.ValorTotal = Convert.ToDecimal(multNet);
                        rrnew.Valor = Convert.ToDecimal(txtNetNetTarifas.Text);
                        rrnew.markup = Convert.ToDecimal(txtMarkupTarifas.Text);
                        rrnew.markupNet = Convert.ToDecimal(txtMarkupNetTarifas.Text);
                        rrnew.desconto = Convert.ToDecimal(txtDescontoTarifas.Text);
                        rrnew.descontoNet = Convert.ToDecimal(txtDescontoNetTarifas.Text);
                        rrnew.Ranges_id = r.Ranges_id;

                        rg.AtualizarValores(rrnew);

                        ftrnew.Qtd_Transf = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftrnew.Paxs = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftrnew.Paying_Pax = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftrnew.Supp_Paying_Pax = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftrnew.File_Transf_id = ftr.File_Transf_id;

                        ftrd.AtualizarNew(ftrnew);

                        PopulaNewQuote(fcd.RetornaQuote(Convert.ToInt32(ftr.File_id)), Convert.ToInt32(ViewState["QuoteAtiva"]));
                        //VerificaRanges(fcd.RetornaQuote(Convert.ToInt32(ftr.File_id)));

                        break;

                    case "extra":

                        //Ranges rrr = rg.ObterPorTarifa(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), IdFtarifas, titulo[0], titulo[1], pars2[0].ToString());

                        File_ServExtra fss = fssd.ObterPorId(IdFtarifas);

                        File_ServExtra ftssnew = new File_ServExtra();

                        Ranges rrrnew = new Ranges();

                        rrrnew.VendaNet = Convert.ToDecimal(addNrNoites);
                        rrrnew.Venda = Convert.ToDecimal(addDescontoNet);
                        rrrnew.ValorTotal = Convert.ToDecimal(multNet);
                        rrrnew.Valor = Convert.ToDecimal(txtNetNetTarifas.Text);
                        rrrnew.markup = Convert.ToDecimal(txtMarkupTarifas.Text);
                        rrrnew.markupNet = Convert.ToDecimal(txtMarkupNetTarifas.Text);
                        rrrnew.desconto = Convert.ToDecimal(txtDescontoTarifas.Text);
                        rrrnew.descontoNet = Convert.ToDecimal(txtDescontoNetTarifas.Text);
                        rrrnew.Ranges_id = r.Ranges_id;

                        rg.AtualizarValores(rrrnew);

                        ftssnew.Qtd_ServExtr = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftssnew.Paxs = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftssnew.Paying_Pax = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftssnew.Supp_Paying_Pax = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftssnew.File_ServExtra_id = fss.File_ServExtra_id;

                        fssd.AtualizarNew(ftssnew);

                        PopulaNewQuote(fcd.RetornaQuote(Convert.ToInt32(fss.File_id)), Convert.ToInt32(ViewState["QuoteAtiva"]));
                        //VerificaRanges(fcd.RetornaQuote(Convert.ToInt32(fss.File_id)));

                        break;
                }

                CarregarFileNumero(sender, e);
                //FileCarrinhoDAL fcd = new FileCarrinhoDAL();                
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void AcertaValoresGridVenda(int IdFtarifas, object sender, EventArgs e)
        {
            try
            {

                FileTarifasDAL ftd = new FileTarifasDAL();
                FileTransfersDAL ftrd = new FileTransfersDAL();
                FileServExtraDAL fssd = new FileServExtraDAL();

                string[] pars2 = ViewState["FlagTarifaClicada"].ToString().Split(',');
                int col = Convert.ToInt32(pars2[1]);

                int numNoites = 1;

                if (pars2[0].ToString().Equals("hotel"))
                {
                    File_Tarifas ft = ftd.ObterPorId(IdFtarifas);
                    numNoites = Convert.ToInt32(ft.NumNoites);
                }


                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                double venda = 0;
                double markup = 0;

                //markup = Convert.ToDouble(txtVendaTarifas.Text) / Convert.ToDouble(txtNetNetTarifas.Text) * 10;
                //txtMarkupTarifas.Text = markup.ToString();


                RangeDal rg = new RangeDal();

                string[] titulo = GridBasesTarifas.HeaderRow.Cells[col].Text.ToString().Split('/');

                Ranges r = new Ranges();

                if (titulo[0].Equals("TC"))
                {
                    string[] titulo2 = GridBasesTarifas.HeaderRow.Cells[col - 1].Text.ToString().Split('/');
                    Ranges er = rg.ObterPorTarifa(IdFtarifas, titulo2[0], titulo2[1], fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), Convert.ToInt32(ViewState["QuoteAtiva"]), pars2[0].ToString());
                    r = rg.ObterPorIdID(er.Ranges_id);
                }
                else
                {
                    r = rg.ObterPorTarifa(IdFtarifas, titulo[0], titulo[1], fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), Convert.ToInt32(ViewState["QuoteAtiva"]), pars2[0].ToString());
                }

                switch (pars2[0].ToString())
                {
                    case "hotel":

                        File_Tarifas ft = ftd.ObterPorId(IdFtarifas);
                        File_Tarifas ftnew = new File_Tarifas();
                        Ranges rnew = rg.ObterPorId(r.Ranges_id);

                        double mult = Convert.ToDouble(txtVendaTarifas.Text) * Convert.ToDouble(numNoites);
                        double mkpNew = ((Convert.ToDouble(txtVendaTarifas.Text) / Convert.ToDouble(txtNetNetTarifas.Text)) * 100) - 100;
                        double vlNew = (Convert.ToDouble(txtNetNetTarifas.Text) * mkpNew) / 100;

                        rnew.VendaNet = Convert.ToDecimal(vlNew) + Convert.ToDecimal(txtNetNetTarifas.Text);
                        rnew.markup = Convert.ToDecimal(mkpNew);
                        rnew.Venda = Convert.ToDecimal(txtVendaTarifas.Text);
                        rnew.VendaNet = Convert.ToDecimal(txtVendaTarifas.Text);
                        rnew.ValorTotal = Convert.ToDecimal(mult);

                        rg.AtualizarValores(rnew);

                        ftnew.Qtd_Tarifas = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftnew.Paxs = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftnew.Paying_Pax = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftnew.Supp_Paying_Pax = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftnew.File_Tarifas_id = ft.File_Tarifas_id;

                        ftd.AtualizarNew(ftnew);

                        PopulaNewQuote(fcd.RetornaQuote(Convert.ToInt32(ft.File_id)), Convert.ToInt32(ViewState["QuoteAtiva"]));
                        break;

                    case "servico":

                        File_Transfers ftr = ftrd.ObterPorId(IdFtarifas);
                        File_Transfers ftrnew = new File_Transfers();
                        Ranges rrnew = rg.ObterPorId(r.Ranges_id);

                        double multsv = Convert.ToDouble(txtVendaTarifas.Text) * Convert.ToDouble(numNoites);
                        double mkpNewsv = ((Convert.ToDouble(txtVendaTarifas.Text) / Convert.ToDouble(txtNetNetTarifas.Text)) * 100) - 100;
                        double vlNewsv = (Convert.ToDouble(txtNetNetTarifas.Text) * mkpNewsv) / 100;

                        rrnew.VendaNet = Convert.ToDecimal(vlNewsv) + Convert.ToDecimal(txtNetNetTarifas.Text);
                        rrnew.markup = Convert.ToDecimal(mkpNewsv);
                        rrnew.Venda = Convert.ToDecimal(txtVendaTarifas.Text);
                        rrnew.VendaNet = Convert.ToDecimal(txtVendaTarifas.Text);
                        rrnew.ValorTotal = Convert.ToDecimal(multsv);

                        rg.AtualizarValores(rrnew);

                        ftrnew.Qtd_Transf = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftrnew.Paxs = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftrnew.Paying_Pax = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftrnew.Supp_Paying_Pax = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftrnew.File_Transf_id = ftr.File_Transf_id;

                        ftrd.AtualizarNew(ftrnew);

                        PopulaNewQuote(fcd.RetornaQuote(Convert.ToInt32(ftr.File_id)), Convert.ToInt32(ViewState["QuoteAtiva"]));
                        break;

                    case "extra":

                        File_ServExtra fss = fssd.ObterPorId(IdFtarifas);
                        File_ServExtra ftssnew = new File_ServExtra();
                        Ranges rrrnew = rg.ObterPorId(r.Ranges_id);

                        double multex = Convert.ToDouble(txtVendaTarifas.Text) * Convert.ToDouble(numNoites);
                        double mkpNewex = ((Convert.ToDouble(txtVendaTarifas.Text) / Convert.ToDouble(txtNetNetTarifas.Text)) * 100) - 100;
                        double vlNewex = (Convert.ToDouble(txtNetNetTarifas.Text) * mkpNewex) / 100;

                        rrrnew.VendaNet = Convert.ToDecimal(vlNewex) + Convert.ToDecimal(txtNetNetTarifas.Text);
                        rrrnew.markup = Convert.ToDecimal(mkpNewex);
                        rrrnew.Venda = Convert.ToDecimal(txtVendaTarifas.Text);
                        rrrnew.VendaNet = Convert.ToDecimal(txtVendaTarifas.Text);
                        rrrnew.ValorTotal = Convert.ToDecimal(multex);

                        rg.AtualizarValores(rrrnew);

                        ftssnew.Qtd_ServExtr = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftssnew.Paxs = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftssnew.Paying_Pax = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftssnew.Supp_Paying_Pax = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftssnew.File_ServExtra_id = fss.File_ServExtra_id;

                        fssd.AtualizarNew(ftssnew);

                        PopulaNewQuote(fcd.RetornaQuote(Convert.ToInt32(fss.File_id)), Convert.ToInt32(ViewState["QuoteAtiva"]));
                        //VerificaRanges(fcd.RetornaQuote(Convert.ToInt32(fss.File_id)));

                        break;
                }

                CarregarFileNumero(sender, e);
                //FileCarrinhoDAL fcd = new FileCarrinhoDAL();                
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void AcertaValoresGridNewFile(int IdFtarifas, object sender, EventArgs e)
        {
            try
            {

                QuoteTarifasDAL ftd = new QuoteTarifasDAL();
                QuoteTransDAL ftrd = new QuoteTransDAL();
                QuoteServExtDAL fssd = new QuoteServExtDAL();


                string[] pars2 = ViewState["FlagTarifaClicadaNewFile"].ToString().Split(',');
                int col = Convert.ToInt32(pars2[1]);

                int numNoites = 1;

                if (pars2[0].ToString().Equals("hotel"))
                {
                    Quote_Tarifas ft = ftd.ObterPorId(IdFtarifas);
                    numNoites = Convert.ToInt32(ft.NumNoites);
                }


                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                int IdFile = fcd.RetornaFile(txtQuoteNumber.Text);

                double venda = 0;


                if (Convert.ToDecimal(txtMarkupTarifas.Text) < 1)
                {
                    venda = (Convert.ToDouble(txtNetNetTarifas.Text) / Convert.ToDouble(txtMarkupTarifas.Text));
                }
                else
                {
                    venda = (Convert.ToDouble(txtNetNetTarifas.Text) * Convert.ToDouble(txtMarkupTarifas.Text) / 100) + Convert.ToDouble(txtNetNetTarifas.Text);
                }

                ArredondaDAL arrd = new ArredondaDAL();

                string[] pars = Convert.ToDecimal(venda).ToString().Split(',');
                decimal valorArr = 0;

                if (pars.Count() > 1)
                {
                    Arredonda arr;

                    if (pars[1].Length == 1)
                    {
                        string val = pars[1] + 0;
                        arr = arrd.ObterArr(Convert.ToInt32(val.Substring(0, 2)));
                    }
                    else
                    {
                        arr = arrd.ObterArr(Convert.ToInt32(pars[1].Substring(0, 2)));
                    }

                    if (arr.Arredonda_recebe < 1)
                    {
                        valorArr = Convert.ToDecimal(pars[0]) + Convert.ToDecimal(arr.Arredonda_recebe);
                        venda = Convert.ToDouble(valorArr);
                    }
                    else
                    {
                        valorArr = Convert.ToDecimal(pars[0]) + Convert.ToDecimal(arr.Arredonda_recebe);
                        venda = Convert.ToDouble(valorArr);
                    }
                }

                double addDesconto = venda - (venda * Convert.ToDouble(txtDescontoTarifas.Text) / 100);

                double addNrNoites = Convert.ToDouble(numNoites) * addDesconto;

                txtVendaTarifas.Text = addNrNoites.ToString("N");

                double addMarkupNet = (Convert.ToDouble(addNrNoites) * Convert.ToDouble(txtMarkupNetTarifas.Text) / 100) + Convert.ToDouble(addNrNoites);

                double addDescontoNet = addMarkupNet - (addMarkupNet * Convert.ToDouble(txtDescontoNetTarifas.Text) / 100);

                double multNet = addDescontoNet;

                txtNetTarifas.Text = addDescontoNet.ToString("N");

                lbltotalTarifas.Text = multNet.ToString("N");

                RangeDal rg = new RangeDal();

                string[] titulo = GridBasesTarifas.HeaderRow.Cells[col].Text.ToString().Split('/');

                switch (pars2[0].ToString())
                {
                    case "hotel":

                        Quote_Tarifas ftnew = new Quote_Tarifas();

                        ftnew.S_merc_tarif_vendaNet = Convert.ToDecimal(addNrNoites);
                        ftnew.S_merc_tarif_venda = Convert.ToDecimal(addDescontoNet);
                        ftnew.S_merc_tarif_total = Convert.ToDecimal(multNet);
                        ftnew.S_merc_tarif_valor = Convert.ToDecimal(txtNetNetTarifas.Text);
                        ftnew.markup = Convert.ToDecimal(txtMarkupTarifas.Text);
                        ftnew.markupNet = Convert.ToDecimal(txtMarkupNetTarifas.Text);
                        ftnew.desconto = Convert.ToDecimal(txtDescontoTarifas.Text);
                        ftnew.descontoNet = Convert.ToDecimal(txtDescontoNetTarifas.Text);
                        ftnew.Qtd_Tarifas = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftnew.Paxs = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftnew.Paying_Pax = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftnew.Supp_Paying_Pax = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftnew.Quote_Tarifas_id = ftd.ObterPorId(IdFtarifas).Quote_Tarifas_id; //ft.Quote_Tarifas_id;

                        ftd.AtualizarNew(ftnew);

                        PopularNewFile();

                        break;

                    case "servico":

                        Quote_Transf ftrnew = new Quote_Transf();

                        ftrnew.S_merc_tarif_vendaNet = Convert.ToDecimal(addNrNoites);
                        ftrnew.Transf_vendaNet = Convert.ToDecimal(addDescontoNet);
                        ftrnew.Transf_venda = Convert.ToDecimal(addDescontoNet);
                        ftrnew.Transf_total = Convert.ToDecimal(multNet);
                        ftrnew.Transf_valor = Convert.ToDecimal(txtNetNetTarifas.Text);
                        ftrnew.markup = Convert.ToDecimal(txtMarkupTarifas.Text);
                        ftrnew.markupNet = Convert.ToDecimal(txtMarkupNetTarifas.Text);
                        ftrnew.desconto = Convert.ToDecimal(txtDescontoTarifas.Text);
                        ftrnew.descontoNet = Convert.ToDecimal(txtDescontoNetTarifas.Text);
                        ftrnew.Qtd_Transf = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftrnew.Paxs = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftrnew.Paying_Pax = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftrnew.Supp_Paying_Pax = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftrnew.Quote_Transf_id = ftrd.ObterPorId(IdFtarifas).Quote_Transf_id;

                        ftrd.AtualizarNew(ftrnew);

                        PopularNewFile();

                        break;

                    case "extra":

                        Quote_ServExtra ftssnew = new Quote_ServExtra();

                        ftssnew.File_ServExtra_vendaNet = Convert.ToDecimal(addNrNoites);
                        ftssnew.File_ServExtra_venda = Convert.ToDecimal(addDescontoNet);
                        ftssnew.File_ServExtra_total = Convert.ToDecimal(multNet);
                        ftssnew.File_ServExtra_valor = Convert.ToDecimal(txtNetNetTarifas.Text);
                        ftssnew.markup = Convert.ToDecimal(txtMarkupTarifas.Text);
                        ftssnew.markupNet = Convert.ToDecimal(txtMarkupNetTarifas.Text);
                        ftssnew.desconto = Convert.ToDecimal(txtDescontoTarifas.Text);
                        ftssnew.descontoNet = Convert.ToDecimal(txtDescontoNetTarifas.Text);
                        ftssnew.Qtd_ServExtr = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftssnew.Paxs = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftssnew.Paying_Pax = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftssnew.Supp_Paying_Pax = Convert.ToInt32(txtPaxsTarifas.Text);
                        ftssnew.Quote_ServExtra_id = fssd.ObterPorId(IdFtarifas).Quote_ServExtra_id;

                        fssd.AtualizarNew(ftssnew);

                        PopularNewFile();

                        break;
                }

                //CarregarFileNumero(sender, e);                         
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void AcertaValoresGridNewFileVenda(int IdFtarifas, object sender, EventArgs e)
        {
            try
            {
                QuoteTarifasDAL qtd = new QuoteTarifasDAL();
                QuoteTransDAL qtrd = new QuoteTransDAL();
                QuoteServExtDAL qssd = new QuoteServExtDAL();

                string[] pars2 = ViewState["FlagTarifaClicadaNewFile"].ToString().Split(',');
                int col = Convert.ToInt32(pars2[1]);

                int numNoites = 1;

                if (pars2[0].ToString().Equals("hotel"))
                {
                    Quote_Tarifas ft = qtd.ObterPorId(IdFtarifas);
                    numNoites = Convert.ToInt32(ft.NumNoites);
                }


                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                RangeDal rg = new RangeDal();

                string[] titulo = GridBasesTarifas.HeaderRow.Cells[col].Text.ToString().Split('/');

                Ranges r = new Ranges();

                if (titulo[0].Equals("TC"))
                {
                    string[] titulo2 = GridBasesTarifas.HeaderRow.Cells[col - 1].Text.ToString().Split('/');
                    Ranges er = rg.ObterPorTarifa(IdFtarifas, titulo2[0], titulo2[1], fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), Convert.ToInt32(ViewState["QuoteAtiva"]), pars2[0].ToString());
                    r = rg.ObterPorIdID(er.Ranges_id);
                }
                else
                {
                    r = rg.ObterPorTarifa(IdFtarifas, titulo[0], titulo[1], fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), Convert.ToInt32(ViewState["QuoteAtiva"]), pars2[0].ToString());
                }

                switch (pars2[0].ToString())
                {
                    case "hotel":

                        Quote_Tarifas ftnew = qtd.ObterPorId(IdFtarifas);

                        double mult = Convert.ToDouble(txtVendaTarifas.Text) * Convert.ToDouble(numNoites);
                        double mkpNew = ((Convert.ToDouble(txtVendaTarifas.Text) / Convert.ToDouble(txtNetNetTarifas.Text)) * 100) - 100;
                        double vlNew = (Convert.ToDouble(txtNetNetTarifas.Text) * mkpNew) / 100;

                        ftnew.S_merc_tarif_vendaNet = Convert.ToDecimal(txtVendaTarifas.Text);
                        ftnew.S_merc_tarif_venda = Convert.ToDecimal(txtVendaTarifas.Text);
                        ftnew.S_merc_tarif_total = Convert.ToDecimal(mult);
                        ftnew.markup = Convert.ToDecimal(mkpNew);

                        qtd.AtualizarNew(ftnew);
                        PopularNewFile();
                        break;

                    case "servico":

                        Quote_Transf ftnew1 = qtrd.ObterPorId(IdFtarifas);

                        double multsv = Convert.ToDouble(txtVendaTarifas.Text) * Convert.ToDouble(numNoites);
                        double mkpNewsv = ((Convert.ToDouble(txtVendaTarifas.Text) / Convert.ToDouble(txtNetNetTarifas.Text)) * 100) - 100;
                        double vlNewsv = (Convert.ToDouble(txtNetNetTarifas.Text) * mkpNewsv) / 100;

                        ftnew1.S_merc_tarif_vendaNet = Convert.ToDecimal(txtVendaTarifas.Text);
                        ftnew1.Transf_venda = Convert.ToDecimal(txtVendaTarifas.Text);
                        ftnew1.Transf_total = Convert.ToDecimal(multsv);
                        ftnew1.markup = Convert.ToDecimal(mkpNewsv);

                        qtrd.AtualizarNew(ftnew1);
                        PopularNewFile();
                        break;

                    case "extra":

                        Quote_ServExtra ftnew2 = qssd.ObterPorId(IdFtarifas);

                        double multex = Convert.ToDouble(txtVendaTarifas.Text) * Convert.ToDouble(numNoites);
                        double mkpNewex = ((Convert.ToDouble(txtVendaTarifas.Text) / Convert.ToDouble(txtNetNetTarifas.Text)) * 100) - 100;
                        double vlNewex = (Convert.ToDouble(txtNetNetTarifas.Text) * mkpNewex) / 100;

                        ftnew2.S_merc_tarif_vendaNet = Convert.ToDecimal(txtVendaTarifas.Text);
                        ftnew2.File_ServExtra_venda = Convert.ToDecimal(txtVendaTarifas.Text);
                        ftnew2.File_ServExtra_total = Convert.ToDecimal(multex);
                        ftnew2.markup = Convert.ToDecimal(mkpNewex);

                        qssd.AtualizarNew(ftnew2);
                        PopularNewFile();

                        break;
                }

                CarregarFileNumero(sender, e);
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void TarifasGrid1_Command(object sender, CommandEventArgs e)
        {
            try
            {

                ViewState["TarifaFile"] = 0;

                RangeDal rd = new RangeDal();
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileTransfersDAL ftrd = new FileTransfersDAL();
                FileServExtraDAL fsvd = new FileServExtraDAL();

                string[] pars = e.CommandArgument.ToString().Split(',');

                //foreach (GridViewRow item in GridBasesTarifas.Rows)
                //{

                int IdFTarifas = Convert.ToInt32(pars[1]);
                int col = Convert.ToInt32(pars[0]);
                //Label lblFlag = (Label)item.FindControl("lblFlag");

                ViewState["IdFTarifasBases"] = IdFTarifas;

                string[] titulo = GridBasesTarifas.HeaderRow.Cells[col].Text.ToString().Split('/');

                if (pars[5].ToString().Equals("True"))
                {
                    imgEditSubServico.Visible = true;
                    ViewState["DadosOpenSubServicos"] = e.CommandArgument.ToString() + "," + titulo[0].ToString() + "," + titulo[1].ToString() + "," + col;
                }
                else
                {
                    imgEditSubServico.Visible = false;
                }

                Ranges r = new Ranges();

                if (titulo[0].Equals("TC"))
                {
                    string[] titulo2 = GridBasesTarifas.HeaderRow.Cells[col - 1].Text.ToString().Split('/');
                    Ranges er = rd.ObterPorTarifa(IdFTarifas, titulo2[0], titulo2[1], pars[2]);
                    r = rd.ObterPorIdID(er.Ranges_id);
                }
                else
                {
                    r = rd.ObterPorTarifa(IdFTarifas, titulo[0], titulo[1], pars[2]);
                }

                //Ranges r = rd.ObterPorTarifa(IdFTarifas, titulo[0], titulo[1]);

                switch (pars[2].ToString())
                {
                    case "hotel":

                        File_Tarifas ft = ftd.ObterPorId(IdFTarifas);

                        if (r.Ranges_de.Equals("TC"))
                        {
                            txtPaxsTarifas.Text = r.QtdTC.ToString();
                            txtSupplierPayPaxs.Text = r.QtdTC.ToString();
                            txtPaxs.Text = r.QtdTC.ToString();
                        }
                        else
                        {
                            txtPaxsTarifas.Text = ft.Paying_Pax.ToString();
                            txtSupplierPayPaxs.Text = ft.Supp_Paying_Pax.ToString();
                            txtPaxs.Text = ft.Paxs.ToString();
                        }

                        txtNetNetTarifas.Text = r.Valor.ToString();
                        txtNetTarifas.Text = r.VendaNet.ToString();
                        txtMarkupTarifas.Text = r.markup.ToString();
                        txtMarkupNetTarifas.Text = r.markupNet.ToString();
                        txtDescontoTarifas.Text = r.desconto.ToString();
                        txtDescontoNetTarifas.Text = r.descontoNet.ToString();
                        txtVendaTarifas.Text = r.Venda.ToString();

                        lblQtdNoitesPopUp.Text = "x" + (Convert.ToDateTime(ft.Data_To) - Convert.ToDateTime(ft.Data_From)).Days.ToString() + " Noites.";

                        lbltotalTarifas.Text = r.ValorTotal.ToString();
                        break;

                    case "servico":

                        lblQtdNoitesPopUp.Text = "";

                        File_Transfers ftr = ftrd.ObterPorId(IdFTarifas);

                        if (r.Ranges_de.Equals("TC"))
                        {
                            txtPaxsTarifas.Text = r.QtdTC.ToString();
                            txtSupplierPayPaxs.Text = r.QtdTC.ToString();
                            txtPaxs.Text = r.QtdTC.ToString();
                        }
                        else
                        {
                            txtPaxsTarifas.Text = ftr.Paying_Pax.ToString();
                            txtSupplierPayPaxs.Text = ftr.Supp_Paying_Pax.ToString();
                            txtPaxs.Text = ftr.Paxs.ToString();
                        }

                        txtNetNetTarifas.Text = r.Valor.ToString();
                        txtNetTarifas.Text = r.VendaNet.ToString();
                        txtMarkupTarifas.Text = r.markup.ToString();
                        txtMarkupNetTarifas.Text = r.markupNet.ToString();
                        txtDescontoTarifas.Text = r.desconto.ToString();
                        txtDescontoNetTarifas.Text = r.descontoNet.ToString();
                        txtVendaTarifas.Text = r.Venda.ToString();

                        lbltotalTarifas.Text = r.ValorTotal.ToString();

                        break;

                    case "extra":

                        lblQtdNoitesPopUp.Text = "";

                        File_ServExtra ftserv = fsvd.ObterPorId(IdFTarifas);

                        if (r.Ranges_de.Equals("TC"))
                        {
                            txtPaxsTarifas.Text = r.QtdTC.ToString();
                            txtSupplierPayPaxs.Text = r.QtdTC.ToString();
                            txtPaxs.Text = r.QtdTC.ToString();
                        }
                        else
                        {
                            txtPaxsTarifas.Text = ftserv.Paying_Pax.ToString();
                            txtSupplierPayPaxs.Text = ftserv.Supp_Paying_Pax.ToString();
                            txtPaxs.Text = ftserv.Paxs.ToString();
                        }

                        txtPaxsTarifas.Text = ftserv.Paying_Pax.ToString();
                        txtNetNetTarifas.Text = r.Valor.ToString();
                        txtNetTarifas.Text = r.VendaNet.ToString();
                        txtMarkupTarifas.Text = r.markup.ToString();
                        txtMarkupNetTarifas.Text = r.markupNet.ToString();
                        txtDescontoTarifas.Text = r.desconto.ToString();
                        txtDescontoNetTarifas.Text = r.descontoNet.ToString();
                        txtVendaTarifas.Text = r.Venda.ToString();

                        lbltotalTarifas.Text = r.ValorTotal.ToString();

                        break;

                }

                //}

                ViewState["FlagTarifaClicada"] = pars[2].ToString() + "," + col;

                ModalPopupExtenderTarifasGrids.Show();

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void ExluirFileCarrinhoTarifas(object sender, CommandEventArgs e)
        {
            try
            {
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                string[] pars = e.CommandArgument.ToString().Split(',');

                int idretorna = Convert.ToInt32(pars[0]);
                string flag = pars[1];
                int IdQuot = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));

                //Ranges r = rd.ObterPorTarifa(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), Convert.ToInt32(IdFileTarifas.Text), Convert.ToInt32(titulo[0]), Convert.ToInt32(titulo[1]), lblFlag.Text);
                //string[] titulo = GridBasesTarifas.HeaderRow.Cells[i].Text.ToString().Split('/');

                RangeDal rg = new RangeDal();

                foreach (var item in rg.ObterPorTarifa(idretorna, IdQuot))
                {
                    rg.Excluir(item);
                }

                switch (flag)
                {
                    case "hotel":
                        FileTarifasDAL ftd = new FileTarifasDAL();
                        File_Tarifas ft = ftd.ObterPorId(idretorna);
                        ftd.Excluir(ft);
                        break;
                    case "servico":
                        FileTransfersDAL fttd = new FileTransfersDAL();
                        File_Transfers ftr = fttd.ObterPorId(idretorna);
                        fttd.Excluir(ftr);
                        break;
                    case "extra":
                        FileServExtraDAL fstd = new FileServExtraDAL();
                        File_ServExtra fse = fstd.ObterPorId(idretorna);
                        fstd.Excluir(fse);
                        break;
                }

                PopulaNewQuote(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToInt32(ViewState["QuoteAtiva"]));
                MostrarMsg("Registro excluído com sucesso.");

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void btnDelColuna_Click(object sender, EventArgs e)
        {
            try
            {
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                RangeDal rd = new RangeDal();

                int IdQuote = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));

                GridDelColunas.DataSource = rd.ListarTodosOrdemDist(IdQuote, Convert.ToInt32(ViewState["QuoteAtiva"]));
                GridDelColunas.DataBind();

                ModalPopupExtenderDelColunas.Show();

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnOrdenarColuna_Click(object sender, EventArgs e)
        {
            try
            {
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                RangeDal rd = new RangeDal();

                int IdQuote = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));

                GridViewOrdenarColunas.DataSource = rd.ListarTodosGroup(IdQuote);
                GridViewOrdenarColunas.DataBind();

                ModalPopupExtenderOrdenarColunas.Show();

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void ExluirColunas_Command(object sender, CommandEventArgs e)
        {
            try
            {
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                RangeDal rd = new RangeDal();

                string[] pars = e.CommandArgument.ToString().Split(',');

                foreach (var item in rd.ObterPorTarifaDeAteOrdem(Convert.ToInt32(pars[2]), pars[0], pars[1], Convert.ToInt32(pars[3]), Convert.ToInt32(ViewState["QuoteAtiva"]))) rd.Excluir(item);

                CarregarFileNumero(sender, e);

                //PopulaNewQuote(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)));
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnOrdenarColunas_Click(object sender, EventArgs e)
        {
            try
            {
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                RangeDal rd = new RangeDal();

                foreach (GridViewRow item in GridViewOrdenarColunas.Rows)
                {
                    TextBox txtOrdem = (TextBox)item.FindControl("txtOrdem");

                    List<Ranges> r = rd.ObterPorTarifaDeAte(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), item.Cells[0].Text, item.Cells[1].Text);

                    foreach (var item2 in r)
                    {
                        Ranges rnew = new Ranges();
                        rnew.Ordem = Convert.ToInt32(txtOrdem.Text);
                        rnew.Ranges_id = item2.Ranges_id;

                        rd.AtualizaOrdem(rnew);
                    }
                }

                PopulaNewQuote(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), Convert.ToInt32(ViewState["QuoteAtiva"]));

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void AtualizarStatusNew(object sender, CommandEventArgs e)
        {
            try
            {
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileTransfersDAL ftrd = new FileTransfersDAL();
                FileServExtraDAL fsed = new FileServExtraDAL();

                string[] pars = e.CommandArgument.ToString().Split(',');

                switch (pars[2].ToString())
                {
                    case "hotel":

                        File_Tarifas ft = new File_Tarifas();

                        if (pars[1].Equals("OR"))
                        {
                            ft.File_Tarifas_id = Convert.ToInt32(pars[0]);
                            ft.Status = "OK";
                        }
                        else
                        {
                            ft.File_Tarifas_id = Convert.ToInt32(pars[0]);
                            ft.Status = "OR";
                        }

                        ftd.AtualizarStatus(ft);

                        break;

                    case "servico":

                        File_Transfers ftr = new File_Transfers();

                        if (pars[1].Equals("OR"))
                        {
                            ftr.File_Transf_id = Convert.ToInt32(pars[0]);
                            ftr.Status = "OK";
                        }
                        else
                        {
                            ftr.File_Transf_id = Convert.ToInt32(pars[0]);
                            ftr.Status = "OR";
                        }

                        ftrd.AtualizarStatus(ftr);


                        break;

                    case "extra":

                        File_ServExtra fsex = new File_ServExtra();

                        if (pars[1].Equals("OR"))
                        {
                            fsex.File_ServExtra_id = Convert.ToInt32(pars[0]);
                            fsex.Status = "OK";
                        }
                        else
                        {
                            fsex.File_ServExtra_id = Convert.ToInt32(pars[0]);
                            fsex.Status = "OR";
                        }

                        fsed.AtualizarStatus(fsex);

                        break;
                }

                MostrarMsg("Status alterado com sucesso.");

                //FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                //PopulaNewQuote(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)));

                CarregarFileNumero(sender, e);
                //PopularGridListCarrinho(Convert.ToInt32(ViewState["IdQuotGrupo"]));
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        protected void AtualizarStatusFileNew(object sender, CommandEventArgs e)
        {
            try
            {
                QuoteTarifasDAL ftd = new QuoteTarifasDAL();
                QuoteTransDAL ftrd = new QuoteTransDAL();
                QuoteServExtDAL fsed = new QuoteServExtDAL();

                string[] pars = e.CommandArgument.ToString().Split(',');

                switch (pars[2].ToString())
                {
                    case "hotel":

                        Quote_Tarifas ft = new Quote_Tarifas();

                        if (pars[1].Equals("OR"))
                        {
                            ft.Quote_Tarifas_id = Convert.ToInt32(pars[0]);
                            ft.Status = "OK";
                        }
                        else
                        {
                            ft.Quote_Tarifas_id = Convert.ToInt32(pars[0]);
                            ft.Status = "OR";
                        }

                        ftd.AtualizarStatus(ft);

                        break;

                    case "servico":

                        Quote_Transf ftr = new Quote_Transf();

                        if (pars[1].Equals("OR"))
                        {
                            ftr.Quote_Transf_id = Convert.ToInt32(pars[0]);
                            ftr.Status = "OK";
                        }
                        else
                        {
                            ftr.Quote_Transf_id = Convert.ToInt32(pars[0]);
                            ftr.Status = "OR";
                        }

                        ftrd.AtualizarStatus(ftr);


                        break;

                    case "extra":

                        Quote_ServExtra fsex = new Quote_ServExtra();

                        if (pars[1].Equals("OR"))
                        {
                            fsex.Quote_ServExtra_id = Convert.ToInt32(pars[0]);
                            fsex.Status = "OK";
                        }
                        else
                        {
                            fsex.Quote_ServExtra_id = Convert.ToInt32(pars[0]);
                            fsex.Status = "OR";
                        }

                        fsed.AtualizarStatus(fsex);

                        break;
                }

                MostrarMsg("Status alterado com sucesso.");

                //FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                //PopulaNewQuote(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)));

                CarregarFileNumero(sender, e);
                //PopularGridListCarrinho(Convert.ToInt32(ViewState["IdQuotGrupo"]));
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        protected void btnAddTC_Click(object sender, EventArgs e)
        {
            try
            {
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                RangeDal rd = new RangeDal();

                int IdQuote = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));

                GridViewAddTc.DataSource = rd.ListarTodosGroup(IdQuote, Convert.ToInt32(ViewState["QuoteAtiva"]));
                GridViewAddTc.DataBind();

                ModalPopupExtenderAddTc.Show();

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnGerarFile_Click(object sender, EventArgs e)
        {
            try
            {

                RangeDal rd = new RangeDal();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileTransfersDAL ftrd = new FileTransfersDAL();

                int IdQuote = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));
                int IdFile = fcd.RetornaFile(txtQuoteNumber.Text);

                int qtdRooms = ftd.RetornaRooms(IdFile, Convert.ToInt32(ViewState["QuoteAtiva"])).Count;
                string[] rooms = new string[qtdRooms];

                DataTable dtRooms = new DataTable();
                dtRooms.Columns.Add("room");
                dtRooms.Columns.Add("ordem");

                foreach (string item in ftd.RetornaRooms(IdFile, Convert.ToInt32(ViewState["QuoteAtiva"])))
                {
                    DataRow dr = dtRooms.NewRow();

                    dr["room"] = item.ToString();

                    switch (item)
                    {
                        case "Single":
                            dr["ordem"] = 1;
                            break;
                        case "Double":
                            dr["ordem"] = 2;
                            break;
                        case "Triple":
                            dr["ordem"] = 3;
                            break;
                    }

                    dtRooms.Rows.Add(dr);
                }

                GridColunasFile.DataSource = rd.ListarTodosGroupNotTC(IdQuote, Convert.ToInt32(ViewState["QuoteAtiva"]));
                GridColunasFile.DataBind();

                DataView dv = dtRooms.DefaultView;
                dv.Sort = "ordem ASC";
                DataTable sortedDT = dv.ToTable();

                GridRooms.DataSource = sortedDT;
                GridRooms.DataBind();

                ModalPopupExtenderGeraFile.Show();

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnSalvaTC_Click(object sender, EventArgs e)
        {
            try
            {
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileTransfersDAL ftrasd = new FileTransfersDAL();
                FileServExtraDAL fserv = new FileServExtraDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                RangeDal rd = new RangeDal();

                int IdQuot = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));

                foreach (Ranges item in rd.ListarTodos(IdQuot, Convert.ToInt32(ViewState["QuoteAtiva"])))
                {
                    Ranges novo = new Ranges();

                    novo.DAY = null;
                    novo.Ranges_id = item.Ranges_id;

                    rd.AtualizarDAY(novo);
                }

                //int i = 8;

                foreach (GridViewRow gridTC in GridViewAddTc.Rows)
                {

                    TextBox txtQtdTC = (TextBox)gridTC.FindControl("txtQtdTC");
                    string De = gridTC.Cells[0].Text;
                    string Ate = gridTC.Cells[1].Text;


                    if (!String.IsNullOrEmpty(txtQtdTC.Text))
                    {
                        List<Ranges> r = rd.ObterPorTarifaDeAteOpt(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), De, Ate, Convert.ToInt32(ViewState["QuoteAtiva"]));

                        foreach (Ranges item in r)
                        {

                            Ranges rnew = new Ranges();
                            rnew.Ranges_de = "TC";
                            rnew.Ranges_ate = "TC";
                            rnew.Quotation_Id = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));
                            rnew.Flag = item.Flag;
                            rnew.RangeID = item.Ranges_id;

                            rnew.QtdTC = Convert.ToInt32(txtQtdTC.Text);

                            rnew.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                            rnew.Ordem = item.Ordem;

                            switch (item.Flag)
                            {
                                case "hotel":
                                    File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(item.FileTabelaId));
                                    rnew.FileTabelaId = ft.File_Tarifas_id;
                                    break;
                                case "servico":
                                    File_Transfers ftr = ftrasd.ObterPorId(Convert.ToInt32(item.FileTabelaId));
                                    rnew.FileTabelaId = ftr.File_Transf_id;
                                    break;
                                case "extra":
                                    File_ServExtra fser = fserv.ObterPorId(Convert.ToInt32(item.FileTabelaId));
                                    rnew.FileTabelaId = fser.File_ServExtra_id;
                                    break;
                            }

                            rnew.markup = item.markup;
                            rnew.desconto = item.desconto;
                            rnew.markupNet = item.markupNet;
                            rnew.descontoNet = item.descontoNet;
                            rnew.VendaNet = item.VendaNet;
                            rnew.Valor = item.Valor;
                            rnew.Venda = item.Venda;
                            rnew.ValorTotal = item.ValorTotal;

                            rd.Salvar(rnew);

                            SubServicosFileDAL ssfdal = new SubServicosFileDAL();

                            List<SubServicosFile> listsub = ssfdal.ListarTodosRange((int)rnew.RangeID, 0);

                            if (listsub.Count > 0)
                            {
                                foreach (var subs in listsub)
                                {
                                    SubServicosFile ssf = new SubServicosFile();
                                    ssf.NomeSupplier = subs.NomeSupplier;
                                    ssf.ServDe = "TC";
                                    ssf.ServAte = "TC";
                                    ssf.NomeFantasia = subs.NomeFantasia;
                                    ssf.NomeSubItem = subs.NomeSubItem;
                                    ssf.Valor = subs.Valor;
                                    ssf.Ranges_id = rnew.Ranges_id;
                                    ssfdal.Salvar(ssf);
                                }
                            }

                        }

                    }


                }

                PopulaNewQuote(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToInt32(ViewState["QuoteAtiva"]));

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnGeraGrade_Click(object sender, EventArgs e)
        {

            string NomeEmpresa = ConfigurationManager.AppSettings["NomeEmpresa"];
            string EnderecoEmpresa = ConfigurationManager.AppSettings["EnderecoEmpresa"];
            string ContatoEmpresa = ConfigurationManager.AppSettings["ContatoEmpresa"];

            DSCotacao ds = new DSCotacao();
            DataTable dt = ds.Tables["Cotacao"];

            RangeDal rg = new RangeDal();
            FileCarrinhoDAL fcd = new FileCarrinhoDAL();

            RptCotacao rpt = new RptCotacao();

            int cont = 1;
            string b;

            bool exists;
            bool flag = true;
            List<string> BasesAdicionadas = new List<string>();


            int IdQuot = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));

            SqlCon Con = new SqlCon();

            Con.AbrirConexao();


            string sql = "";
            sql = sql + "SELECT DISTINCT File_Tarifas.S_nome AS Nome, File_Tarifas.Data_From As dtFrom, Ranges.Flag As Flag, Ranges.Ranges_id As ID, Ranges.Ordem As Ordem, Ranges.Ranges_de As De ";
            sql = sql + "FROM File_Carrinho INNER JOIN File_Tarifas ON File_Carrinho.File_id = File_Tarifas.File_id INNER JOIN ";
            sql = sql + "Ranges ON File_Tarifas.File_Tarifas_id = Ranges.FileTabelaId ";
            sql = sql + "WHERE (Ranges.Quotation_Id = " + IdQuot + ") and (Ranges.Flag = 'hotel') AND (Ranges.OptQuote = " + Convert.ToInt32(ViewState["QuoteAtiva"]) + ") ";
            sql = sql + "UNION ALL ";
            sql = sql + "SELECT DISTINCT File_Transfers.Transf_nome AS Nome, File_Transfers.Data_From As dtFrom, Ranges_1.Flag As Flag, Ranges_1.Ranges_id As ID, Ranges_1.Ordem As Ordem, Ranges_1.Ranges_de As De ";
            sql = sql + "FROM File_Carrinho AS File_Carrinho_1 INNER JOIN File_Transfers ON File_Carrinho_1.File_id = File_Transfers.File_id ";
            sql = sql + "INNER JOIN Ranges AS Ranges_1 ON File_Transfers.File_Transf_id = Ranges_1.FileTabelaId ";
            sql = sql + "WHERE (Ranges_1.Quotation_Id = " + IdQuot + ") and (Ranges_1.Flag = 'servico') AND (Ranges_1.OptQuote = " + Convert.ToInt32(ViewState["QuoteAtiva"]) + ") ";
            sql = sql + "UNION ALL ";
            sql = sql + "SELECT DISTINCT File_ServExtra.File_ServExtra_nome AS Nome, File_ServExtra.Data_From As dtFrom, Ranges_2.Flag As Flag, Ranges_2.Ranges_id As ID, Ranges_2.Ordem As Ordem, Ranges_2.Ranges_de As De ";
            sql = sql + "FROM File_Carrinho AS File_Carrinho_2 INNER JOIN File_ServExtra ON File_Carrinho_2.File_id = File_ServExtra.File_id ";
            sql = sql + "INNER JOIN Ranges AS Ranges_2 ON File_ServExtra.File_ServExtra_id = Ranges_2.FileTabelaId ";
            sql = sql + "WHERE (Ranges_2.Quotation_Id = " + IdQuot + ") and (Ranges_2.Flag = 'extra') AND (Ranges_2.OptQuote = " + Convert.ToInt32(ViewState["QuoteAtiva"]) + ") ";
            sql = sql + "order by dtFrom, Nome, Ordem ";

            Con.Cmd = new SqlCommand(sql, Con.Con);
            Con.Dr = Con.Cmd.ExecuteReader();

            int prdata = 0;
            int ij = 1;
            DateTime dataInicio = DateTime.Now;

            while (Con.Dr.Read())
            {

                if (prdata == 0)
                {
                    dataInicio = Convert.ToDateTime(Con.Dr["dtFrom"]);
                    prdata = 1;
                }

                Ranges r = new Ranges();

                if (Convert.ToDateTime(Con.Dr["dtFrom"]) != dataInicio)
                {
                    double difer = (Convert.ToDateTime(Con.Dr["dtFrom"]) - Convert.ToDateTime(dataInicio)).TotalDays;

                    ij = ij + Convert.ToInt32(difer);
                    dataInicio = Convert.ToDateTime(Con.Dr["dtFrom"]);
                }

                r.DAY = ij;
                r.Ranges_id = Convert.ToInt32(Con.Dr["ID"]);

                rg.AtualizarDAY(r);
            }

            string valor;
            int c = 0;
            bool criaHead = true;

            int qtdBases = rg.QtdBases(IdQuot);
            List<string> basesRodape = new List<string>();

            //string[] valores = AddValorTotalGrade().Split('/');
            string valoresDentro = "";

            foreach (GridViewRow item in GridBasesTarifas.Rows)
            {
                for (int i = 0; i < rg.QtdBases(IdQuot, Convert.ToInt32(ViewState["QuoteAtiva"])); i++)
                {
                    LinkButton lblValor = (LinkButton)item.FindControl(CriaNomeLabel(i + 8));

                    if (valoresDentro.Equals(""))
                    {
                        valoresDentro = lblValor.Text;
                    }
                    else
                    {
                        valoresDentro = valoresDentro + "/" + lblValor.Text;
                    }
                }
            }

            int contadorBases = 1;

            string[] valores = valoresDentro.Split('/');

            PopulaNewQuote(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToInt32(ViewState["QuoteAtiva"]));

            foreach (GridViewRow item in GridBasesTarifas.Rows)
            {
                DataRow dr2 = dt.NewRow();

                /////////////////////////////////////Cria cabeçalho

                if (criaHead)
                {
                    foreach (Ranges it in rg.ListarTodos(IdQuot, Convert.ToInt32(ViewState["QuoteAtiva"])))
                    {
                        if (!it.Ranges_de.Equals("TC"))
                        {
                            exists = BasesAdicionadas.Exists(element => element.Equals(it.Ranges_de));
                            flag = true;
                        }
                        else
                        {
                            exists = false;
                        }

                        if (flag && !exists)
                        {
                            BasesAdicionadas.Add(it.Ranges_de);

                            b = "B" + cont;
                            dr2[b] = it.Ranges_de + "/" + it.Ranges_ate;

                            basesRodape.Add(it.Ranges_de + "/" + it.Ranges_ate);

                            cont += 1;

                            if (it.Ranges_de.Equals("TC"))
                            {
                                flag = false;
                            }
                        }
                    }

                    contadorBases = 1;

                    foreach (string bases in basesRodape)
                    {
                        string nomeBa = "Ba" + contadorBases;

                        CrystalDecisions.CrystalReports.Engine.TextObject Objba1 = rpt.ReportDefinition.Sections[1].ReportObjects[nomeBa] as TextObject;
                        Objba1.Text = bases.ToString();

                        contadorBases++;
                    }

                    contadorBases = 1;

                    if (rg.VerificaExisteTC(IdQuot, Convert.ToInt32(ViewState["QuoteAtiva"])))
                    {
                        List<string> valoTC = new List<string>();
                        List<string> nomeRoomTC = new List<string>();

                        foreach (DataRow vTC in GeraTotalNewQuoteTC().Rows)
                        {
                            valoTC.Add(vTC["Total"].ToString() + "/" + vTC["Room"].ToString());
                            nomeRoomTC.Add(vTC["Room"].ToString());
                        }

                        contadorBases = 0;

                        foreach (string room in nomeRoomTC.Distinct())
                        {
                            string nomeBa = "TotalTc" + contadorBases;
                            CrystalDecisions.CrystalReports.Engine.TextObject ObjtxtValTC = rpt.ReportDefinition.Sections[1].ReportObjects[nomeBa] as TextObject;
                            ObjtxtValTC.Text = "Total per TC in " + room + " :";

                            contadorBases++;
                        }

                        contadorBases = 2;

                        foreach (Ranges rang in rg.ListarTodosGroup(IdQuot, Convert.ToInt32(ViewState["QuoteAtiva"])))
                        {
                            if (!rang.Ranges_de.Equals("TC"))
                            {
                                foreach (string room in nomeRoomTC)
                                {
                                    switch (room)
                                    {
                                        case "Single":

                                            foreach (string f in valoTC)
                                            {
                                                string[] comp = f.ToString().Split('/');

                                                if (comp[1].Equals("Single"))
                                                {
                                                    string nomeBa = "ValTcSingle" + contadorBases;
                                                    CrystalDecisions.CrystalReports.Engine.TextObject ObjValtc1 = rpt.ReportDefinition.Sections[1].ReportObjects[nomeBa] as TextObject;
                                                    ObjValtc1.Text = comp[0].ToString();

                                                    if (nomeRoomTC == null)
                                                    {
                                                        contadorBases++;
                                                    }
                                                    else
                                                    {
                                                        contadorBases = contadorBases + 2;
                                                    }
                                                }
                                            }

                                            nomeRoomTC = nomeRoomTC.Where(val => !val.Equals("Single")).ToList();

                                            contadorBases = 2;
                                            break;

                                        case "Double":

                                            foreach (string f in valoTC)
                                            {
                                                string[] comp = f.ToString().Split('/');

                                                if (comp[1].Equals("Double"))
                                                {
                                                    string nomeBa = "ValTcDouble" + contadorBases;
                                                    CrystalDecisions.CrystalReports.Engine.TextObject ObjValtc2 = rpt.ReportDefinition.Sections[1].ReportObjects[nomeBa] as TextObject;
                                                    ObjValtc2.Text = comp[0].ToString();

                                                    if (nomeRoomTC == null)
                                                    {
                                                        contadorBases++;
                                                    }
                                                    else
                                                    {
                                                        contadorBases = contadorBases + 2;
                                                    }
                                                }
                                            }

                                            nomeRoomTC = nomeRoomTC.Where(val => !val.Equals("Double")).ToList();

                                            contadorBases = 2;
                                            break;

                                        case "Triple":

                                            foreach (string f in valoTC)
                                            {
                                                string[] comp = f.ToString().Split('/');

                                                if (comp[1].Equals("Triple"))
                                                {
                                                    string nomeBa = "ValTcTriple" + contadorBases;
                                                    CrystalDecisions.CrystalReports.Engine.TextObject ObjValtc3 = rpt.ReportDefinition.Sections[1].ReportObjects[nomeBa] as TextObject;
                                                    ObjValtc3.Text = comp[0].ToString();

                                                    if (nomeRoomTC == null)
                                                    {
                                                        contadorBases++;
                                                    }
                                                    else
                                                    {
                                                        contadorBases = contadorBases + 2;
                                                    }
                                                }
                                            }

                                            nomeRoomTC = nomeRoomTC.Where(val => !val.Equals("Double")).ToList();

                                            contadorBases = 2;
                                            break;
                                    }

                                    //break;
                                }
                            }
                        }

                    }

                    List<string> valo = new List<string>();
                    List<string> nomeRoom = new List<string>();

                    foreach (DataRow v in GeraTotalNewQuote().Rows)
                    {
                        valo.Add(v["Total"].ToString() + "/" + v["Room"].ToString());
                        nomeRoom.Add(v["Room"].ToString());
                    }

                    contadorBases = 0;

                    foreach (string room in nomeRoom.Distinct())
                    {
                        string nomeBa = "txtTotalRoom" + contadorBases;
                        CrystalDecisions.CrystalReports.Engine.TextObject ObjtxtVal = rpt.ReportDefinition.Sections[1].ReportObjects[nomeBa] as TextObject;
                        ObjtxtVal.Text = "Total per person in " + room + " :";

                        contadorBases++;
                    }

                    contadorBases = 1;

                    //for (int i = 0; i < rg.ListarTodosGroup(IdQuot).Count; i++)
                    foreach (Ranges rang in rg.ListarTodosGroup(IdQuot, Convert.ToInt32(ViewState["QuoteAtiva"])))
                    {
                        if (!rang.Ranges_de.Equals("TC"))
                        {
                            foreach (string room in nomeRoom)
                            {
                                switch (room)
                                {
                                    case "Single":

                                        foreach (string f in valo)
                                        {
                                            string[] comp = f.ToString().Split('/');

                                            if (comp[1].Equals("Single"))
                                            {
                                                string nomeBa = "ValSingle" + contadorBases;
                                                CrystalDecisions.CrystalReports.Engine.TextObject ObjVal1 = rpt.ReportDefinition.Sections[1].ReportObjects[nomeBa] as TextObject;
                                                ObjVal1.Text = comp[0].ToString();

                                                if (rg.VerificaExisteTC(IdQuot, Convert.ToInt32(ViewState["QuoteAtiva"])))
                                                {
                                                    contadorBases = contadorBases + 2;
                                                }
                                                else
                                                {
                                                    contadorBases++;
                                                }
                                            }
                                        }

                                        nomeRoom = nomeRoom.Where(val => !val.Equals("Single")).ToList();

                                        contadorBases = 1;
                                        break;

                                    case "Double":

                                        foreach (string f in valo)
                                        {
                                            string[] comp = f.ToString().Split('/');

                                            if (comp[1].Equals("Double"))
                                            {
                                                string nomeBa = "ValDouble" + contadorBases;
                                                CrystalDecisions.CrystalReports.Engine.TextObject ObjVall1 = rpt.ReportDefinition.Sections[1].ReportObjects[nomeBa] as TextObject;
                                                ObjVall1.Text = comp[0].ToString();

                                                if (rg.VerificaExisteTC(IdQuot, Convert.ToInt32(ViewState["QuoteAtiva"])))
                                                {
                                                    contadorBases = contadorBases + 2;
                                                }
                                                else
                                                {
                                                    contadorBases++;
                                                }
                                            }
                                        }

                                        nomeRoom = nomeRoom.Where(val => !val.Equals("Double")).ToList();
                                        contadorBases = 1;
                                        break;

                                    case "Triple":

                                        foreach (string f in valo)
                                        {
                                            string[] comp = f.ToString().Split('/');

                                            if (comp[1].Equals("Triple"))
                                            {
                                                string nomeBa = "ValTriple" + contadorBases;
                                                CrystalDecisions.CrystalReports.Engine.TextObject ObjValll1 = rpt.ReportDefinition.Sections[1].ReportObjects[nomeBa] as TextObject;
                                                ObjValll1.Text = comp[0].ToString();

                                                if (rg.VerificaExisteTC(IdQuot, Convert.ToInt32(ViewState["QuoteAtiva"])))
                                                {
                                                    contadorBases = contadorBases + 2;
                                                }
                                                else
                                                {
                                                    contadorBases++;
                                                }
                                            }
                                        }

                                        nomeRoom = nomeRoom.Where(val => !val.Equals("Triple")).ToList();
                                        contadorBases = 1;
                                        break;
                                }

                                //break;

                            }

                            contadorBases = 1;
                        }
                        else
                        {
                            contadorBases++;
                        }
                    }


                    criaHead = false;
                }

                ////////////////////////////////////               


                Label lblNomeSupplier = (Label)item.FindControl("lblNomeSupplier");
                Label lblDAY = (Label)item.FindControl("lblDAY");
                Label lblCidade = (Label)item.FindControl("lblCidade");
                Label lblRoom = (Label)item.FindControl("lblRoom");
                Label lblCategoria = (Label)item.FindControl("lblCategoria");
                Label lblFrom = (Label)item.FindControl("lblFrom");
                Label lblTo = (Label)item.FindControl("lblTo");

                double nights = (Convert.ToDateTime(lblTo.Text) - Convert.ToDateTime(lblFrom.Text)).TotalDays;

                //new FileCarrinhoDAL().MontaCarrinhoNewFile(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToInt32(ViewState["QuoteAtiva"]));
                Utils ut = new Utils();

                string dateRepl = ut.AdjustDate(lblFrom.ToolTip);

                dr2["Day"] = "Day " + lblDAY.Text + " - " + string.Format(new System.Globalization.CultureInfo("en-GB"), "{0:MMM, dd yy}", Convert.ToDateTime(dateRepl)) + " - " + lblCidade.Text;

                string cocatena = "";

                if (!lblRoom.Text.Equals(""))
                {
                    cocatena = " - " + lblRoom.Text + " " + lblCategoria.Text + " x " + nights + " Nights";
                }

                dr2["Nome"] = lblNomeSupplier.Text + cocatena;

                for (int i = 0; i < rg.QtdBases(IdQuot, Convert.ToInt32(ViewState["QuoteAtiva"])); i++)
                {
                    valor = "Valor" + (i + 1);

                    dr2[valor] = valores[0];
                    valores[0] = null;
                    valores = valores.Where(val => val != null).ToArray();

                    c++;
                }

                dt.Rows.Add(dr2);
                c = 0;
            }

            Con.Cmd.Dispose();
            Con.Dr.Dispose();
            Con.FecharConexao();

            CrystalDecisions.CrystalReports.Engine.TextObject ObjNomeEmpresa = rpt.ReportDefinition.Sections[1].ReportObjects["NomeEmpresa"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject ObjEnderecoEmpresa = rpt.ReportDefinition.Sections[1].ReportObjects["EnderecoEmpresa"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject ObjContatoEmpresa = rpt.ReportDefinition.Sections[1].ReportObjects["ContatoEmpresa"] as TextObject;
            ObjNomeEmpresa.Text = NomeEmpresa;
            ObjEnderecoEmpresa.Text = EnderecoEmpresa;
            ObjContatoEmpresa.Text = ContatoEmpresa;

            CrystalDecisions.CrystalReports.Engine.TextObject ObjPara = rpt.ReportDefinition.Sections[1].ReportObjects["txtNomeTo"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject ObjAtt = rpt.ReportDefinition.Sections[1].ReportObjects["txtNomeAtt"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject ObjRef = rpt.ReportDefinition.Sections[1].ReportObjects["txtNomeRef"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject ObjFrom = rpt.ReportDefinition.Sections[1].ReportObjects["txtFrom"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject ObjFile = rpt.ReportDefinition.Sections[1].ReportObjects["txtFile"] as TextObject;
            ObjPara.Text = txtNomeGrupo.Text;
            ObjAtt.Text = ddlCliente.SelectedItem.ToString();
            ObjRef.Text = "";
            ObjFrom.Text = ddlUsuario.SelectedItem.ToString();
            ObjFile.Text = txtQuoteNumber.Text;

            rpt.SetDataSource(dt);

            //rpt.ExportToHttpResponse(
            //            ExportFormatType.WordForWindows,
            //            Response, true, "cotação");

            rpt.ExportToHttpResponse(
                ExportFormatType.PortableDocFormat,
                Response, true, "cotação");

            //switch (ddlFormato.SelectedValue)
            //{
            //    case "1":
            //        rpt3.ExportToHttpResponse(
            //            ExportFormatType.PortableDocFormat,
            //            Response, true, "voucher");
            //        break;

            //    case "2":
            //        rpt3.ExportToHttpResponse(
            //            ExportFormatType.WordForWindows,
            //            Response, true, "voucher");
            //        break;

            //    case "3":
            //        rpt3.ExportToHttpResponse(
            //            ExportFormatType.Excel,
            //            Response, true, "voucher");
            //        break;
            //}

        }

        protected string AddValorTotalGrade()
        {
            string retorno = "";
            FileCarrinhoDAL fcd = new FileCarrinhoDAL();
            RangeDal rg = new RangeDal();

            try
            {
                int num = 1;
                string valor;
                bool exists2;
                bool flag2 = true;
                bool jrange = false;
                List<string> BasesAdicionadas2 = new List<string>();
                List<int> RangesID = new List<int>();

                SqlCon Con2 = new SqlCon();

                int IdQuot = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));

                string De, Ate;

                De = rg.ObterPorTarifaOne(IdQuot).Ranges_de;
                Ate = rg.ObterPorTarifaOne(IdQuot).Ranges_ate;

                for (int j = 1; j <= rg.QtdBases(IdQuot, De, Ate); j++)
                {
                    int quantidade = rg.QtdBases(IdQuot, De, Ate);

                    foreach (Ranges item in rg.ListarTodosOrdenado(IdQuot))
                    {

                        if (!item.Ranges_de.Equals("TC"))
                        {
                            exists2 = BasesAdicionadas2.Exists(element => element.Equals(item.Ranges_de));
                            flag2 = true;
                        }
                        else
                        {
                            exists2 = false;
                            jrange = RangesID.Exists(e => e.Equals(item.RangeID));
                        }

                        if (flag2 && !exists2 && !jrange)
                        {
                            BasesAdicionadas2.Add(item.Ranges_de);

                            if (item.RangeID != null)
                            {
                                RangesID.Add(Convert.ToInt32(item.RangeID));
                            }

                            string BaseDe, BaseAte;
                            if (item.Ranges_de.Equals("TC"))
                            { BaseDe = "'TC'"; BaseAte = "'TC'"; }
                            else
                            { BaseDe = "'" + item.Ranges_de + "'"; BaseAte = "'" + item.Ranges_ate + "'"; }

                            string sql2 = "";

                            if (item.Ranges_de.Equals("TC"))
                            {
                                sql2 = sql2 + "SELECT TOP 1 * FROM (SELECT TOP " + j + " * FROM Ranges ";
                                sql2 = sql2 + "WHERE (Quotation_Id = " + IdQuot + ") AND (Ranges_de = " + BaseDe + ") AND (Ranges_ate = " + BaseAte + ") ";
                                sql2 = sql2 + "AND (RangeID = " + item.RangeID + ") ORDER BY Ranges_id)z ORDER BY Ranges_id DESC";
                            }
                            else
                            {
                                sql2 = sql2 + "SELECT TOP 1 * FROM (SELECT TOP " + j + " * FROM Ranges ";
                                sql2 = sql2 + "WHERE (Quotation_Id = " + IdQuot + ") AND (Ranges_de = " + BaseDe + ") AND (Ranges_ate = " + BaseAte + ") ";
                                sql2 = sql2 + "ORDER BY Ranges_id)z ORDER BY Ranges_id DESC";
                            }

                            Con2.AbrirConexao();
                            Con2.Cmd = new SqlCommand(sql2, Con2.Con);
                            Con2.Dr = Con2.Cmd.ExecuteReader();

                            while (Con2.Dr.Read())
                            {
                                if (retorno.Equals(""))
                                {
                                    retorno = Con2.Dr["ValorTotal"].ToString();
                                }
                                else
                                {
                                    retorno = retorno + "/" + Con2.Dr["ValorTotal"].ToString();
                                }
                                num++;
                            }

                            if (item.Ranges_de.Equals("TC"))
                            {
                                flag2 = false;
                            }

                            Con2.Cmd.Dispose();
                            Con2.Dr.Dispose();
                            Con2.FecharConexao();
                        }

                    }

                    num = 1;
                    exists2 = true;
                    flag2 = true;
                    BasesAdicionadas2.Clear();
                }

                return retorno;

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }

            return retorno;
        }

        protected string CriaNomeLabel(int num)
        {
            return "lnkValorTotalHotel" + num;
        }

        protected DataTable GeraTotalNewQuote()
        {

            DataTable dt = new DataTable();
            try
            {
                dt.Columns.Add("Total");
                dt.Columns.Add("Room");
                dt.Columns.Add("Base");
                dt.Columns.Add("Ordem");


                FileTarifasDAL ftd = new FileTarifasDAL();
                FileTransfersDAL ftrd = new FileTransfersDAL();
                FileServExtraDAL fsed = new FileServExtraDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                RangeDal rg = new RangeDal();

                int IdQuot = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));
                int IdFile = fcd.RetornaFile(txtQuoteNumber.Text);
                decimal total = 0;

                int qtdBases = rg.ListarTodosGroupNotTC(IdQuot, Convert.ToInt32(ViewState["QuoteAtiva"])).Count;
                int qtdRooms = ftd.RetornaRooms(IdFile, Convert.ToInt32(ViewState["QuoteAtiva"])).Count;
                string[] rooms = new string[qtdRooms];
                string[] bases = new string[qtdBases];
                int con = 0;
                int qtdTC = 0;

                foreach (Ranges item in rg.ListarTodosGroup(IdQuot, Convert.ToInt32(ViewState["QuoteAtiva"])))
                {
                    if (!item.Ranges_de.Equals("TC"))
                    {
                        bases[con] = item.Ranges_de + " to " + item.Ranges_ate;
                        con++;
                    }
                }

                con = 0;

                foreach (string item in ftd.RetornaRooms(IdFile, Convert.ToInt32(ViewState["QuoteAtiva"])))
                {
                    rooms[con] = item;
                    con++;
                }

                con = 0;

                int flag = 0;

                File_Tarifas ft = new File_Tarifas();
                File_Transfers ftrans = new File_Transfers();
                File_ServExtra fservext = new File_ServExtra();

                //for (int i = 0; i < qtdRooms; i++)
                for (int i = 0; i < qtdBases; i++)
                {
                    if (flag == 0)
                    {
                        string de = bases[i].ToString().Substring(0, 2).Trim();
                        string ate = bases[i].Substring(bases[i].Length - 2).Trim();

                        for (int j = 0; j < qtdRooms; j++)
                        {
                            DataRow dr = dt.NewRow();

                            foreach (Ranges item in rg.ObterPorTarifaDeAteOpt(IdQuot, de, ate, Convert.ToInt32(ViewState["QuoteAtiva"])))
                            {
                                if (item.Flag.Equals("hotel"))
                                {
                                    ft = ftd.ObterPorId(Convert.ToInt32(item.FileTabelaId));

                                    if (ft.TBulk == true)
                                    {
                                        if (rooms[con].Equals(ft.Room))
                                        {
                                            total = total + Convert.ToDecimal((Convert.ToDecimal(item.ValorTotal) / Convert.ToDecimal(item.Ranges_de)));
                                            total = Math.Round(total, 2);
                                        }
                                    }
                                    else
                                    {
                                        if (rooms[con].Equals(ft.Room))
                                        {
                                            total = total + Convert.ToDecimal(item.ValorTotal);
                                        }

                                        if (ft.Meal == true && ft.S_meal_status == null)
                                        {
                                            total = total + Convert.ToDecimal(item.ValorTotal);
                                        }
                                    }
                                }
                                else if (item.Flag.Equals("servico"))
                                {
                                    ftrans = ftrd.ObterPorId(Convert.ToInt32(item.FileTabelaId));

                                    if (ftrans.TBulk == true)
                                    {
                                        total = total + (Convert.ToDecimal(item.ValorTotal) / Convert.ToDecimal(item.Ranges_de));
                                    }
                                    else
                                    {
                                        total = total + Convert.ToDecimal(item.ValorTotal);
                                    }
                                }
                                else if (item.Flag.Equals("extra"))
                                {
                                    fservext = fsed.ObterPorId(Convert.ToInt32(item.FileTabelaId));

                                    if (fservext.TBulk == true)
                                    {
                                        total = total + (Convert.ToDecimal(item.ValorTotal) / Convert.ToDecimal(item.Ranges_de));
                                    }
                                    else
                                    {
                                        total = total + Convert.ToDecimal(item.ValorTotal);
                                    }
                                }
                            }


                            switch (rooms[con])
                            {
                                case "Single":
                                    dr["Room"] = "Single";
                                    dr["Base"] = bases[i];
                                    dr["Total"] = total;
                                    dr["Ordem"] = 1;
                                    break;
                                case "Double":
                                    dr["Room"] = "Double";
                                    dr["Base"] = bases[i];
                                    dr["Total"] = total;
                                    dr["Ordem"] = 2;
                                    break;
                                case "Triple":
                                    dr["Room"] = "Triple";
                                    dr["Base"] = bases[i];
                                    dr["Total"] = total;
                                    dr["Ordem"] = 3;
                                    break;
                            }

                            total = 0;

                            dt.Rows.Add(dr);

                            con++;
                        }
                        con = 0;

                        if (qtdBases == 1)
                        {
                            flag = 1;
                        }

                    }
                }


                DataView dv = dt.DefaultView;
                dv.Sort = "Ordem ASC";
                DataTable sortedDT = dv.ToTable();

                //DataListRates.DataSource = sortedDT;
                //DataListRates.DataBind();

                return sortedDT;

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }

            return dt;
        }

        protected DataTable GeraTotalNewQuoteTC()
        {

            DataTable dt = new DataTable();
            try
            {
                dt.Columns.Add("Total");
                dt.Columns.Add("Room");
                dt.Columns.Add("Base");
                dt.Columns.Add("Ordem");


                FileTarifasDAL ftd = new FileTarifasDAL();
                FileTransfersDAL ftrd = new FileTransfersDAL();
                FileServExtraDAL fsed = new FileServExtraDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                RangeDal rg = new RangeDal();

                int IdQuot = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));
                int IdFile = fcd.RetornaFile(txtQuoteNumber.Text);
                decimal total = 0;

                //int qtdBases = rg.ListarTodosGroup(IdQuot).Count;
                int qtdBases = rg.QtdBasesTC(IdQuot, Convert.ToInt32(ViewState["QuoteAtiva"]));
                int qtdRooms = ftd.RetornaRooms(IdFile, Convert.ToInt32(ViewState["QuoteAtiva"])).Count;
                string[] rooms = new string[qtdRooms];
                string[] bases = new string[qtdBases];
                int con = 0;
                int qtdTC = 0;


                foreach (Ranges item in rg.ListarTodosGroup(IdQuot, Convert.ToInt32(ViewState["QuoteAtiva"])))
                {
                    if (!item.Ranges_de.Equals("TC"))
                    {
                        bases[con] = item.Ranges_de + " to " + item.Ranges_ate;
                        con++;
                    }
                }

                con = 0;

                foreach (string item in ftd.RetornaRooms(IdFile, Convert.ToInt32(ViewState["QuoteAtiva"])))
                {
                    rooms[con] = item;
                    con++;
                }

                con = 0;

                File_Tarifas ft = new File_Tarifas();
                File_Transfers ftrans = new File_Transfers();
                File_ServExtra fservext = new File_ServExtra();

                //for (int i = 0; i < qtdRooms; i++)
                for (int i = 0; i < qtdBases; i++)
                {
                    for (int j = 0; j < qtdRooms; j++)
                    {
                        string de = bases[i].ToString().Substring(0, 2);

                        DataRow dr = dt.NewRow();

                        if (rg.VerificaSeTC(IdQuot, de))
                        {
                            foreach (Ranges item in rg.RetornaListaTCPBase(IdQuot, de))
                            {
                                if (item.Flag.Equals("hotel"))
                                {
                                    ft = ftd.ObterPorId(Convert.ToInt32(item.FileTabelaId));

                                    if (ft.TBulk == true)
                                    {
                                        if (rooms[con].Equals(ft.Room))
                                        {
                                            total = total + (Convert.ToDecimal(item.ValorTotal) / Convert.ToDecimal(de));
                                            total = Math.Round(total, 2);
                                        }
                                    }
                                    else
                                    {
                                        if (rooms[con].Equals(ft.Room))
                                        {
                                            total = total + Convert.ToDecimal(item.ValorTotal);
                                        }

                                        if (ft.Meal == true && ft.S_meal_status == null)
                                        {
                                            total = total + Convert.ToDecimal(item.ValorTotal);
                                        }
                                    }
                                }
                                else if (item.Flag.Equals("servico"))
                                {
                                    ftrans = ftrd.ObterPorId(Convert.ToInt32(item.FileTabelaId));

                                    if (ftrans.TBulk == true)
                                    {
                                        total = total + (Convert.ToDecimal(item.ValorTotal) / Convert.ToDecimal(de));
                                    }
                                    else
                                    {
                                        total = total + Convert.ToDecimal(item.ValorTotal);
                                    }
                                }
                                else if (item.Flag.Equals("extra"))
                                {
                                    fservext = fsed.ObterPorId(Convert.ToInt32(item.FileTabelaId));

                                    if (fservext.TBulk == true)
                                    {
                                        total = total + (Convert.ToDecimal(item.ValorTotal) / Convert.ToDecimal(de));
                                    }
                                    else
                                    {
                                        total = total + Convert.ToDecimal(item.ValorTotal);
                                    }
                                }
                            }


                            switch (rooms[con])
                            {
                                case "Single":
                                    dr["Room"] = "Single";
                                    dr["Base"] = bases[i];
                                    dr["Total"] = total;
                                    dr["Ordem"] = 1;
                                    break;
                                case "Double":
                                    dr["Room"] = "Double";
                                    dr["Base"] = bases[i];
                                    dr["Total"] = total;
                                    dr["Ordem"] = 2;
                                    break;
                                case "Triple":
                                    dr["Room"] = "Triple";
                                    dr["Base"] = bases[i];
                                    dr["Total"] = total;
                                    dr["Ordem"] = 3;
                                    break;
                            }
                        }

                        total = 0;
                        dt.Rows.Add(dr);
                        con++;
                    }

                    con = 0;
                }

                DataView dv = dt.DefaultView;
                dv.Sort = "Ordem ASC";
                DataTable sortedDT = dv.ToTable();

                //DataListRates.DataSource = sortedDT;
                //DataListRates.DataBind();

                return sortedDT;

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }

            return dt;
        }

        protected void txtQtd_TextChanged(object sender, EventArgs e)
        {
            try
            {

                foreach (GridViewRow item in GridRooms.Rows)
                {

                    Label lblqtdRooms = (Label)item.FindControl("lblqtdRooms");
                    TextBox txtQtd = (TextBox)item.FindControl("txtQtd");
                    string room = item.Cells[0].Text;

                    switch (room)
                    {
                        case "Single":
                            lblqtdRooms.Text = txtQtd.Text;
                            break;

                        case "Double":

                            if (!txtQtd.Text.Equals("") && Convert.ToInt32(txtQtd.Text) == 1)
                            {
                                lblqtdRooms.Text = txtQtd.Text;
                            }
                            else
                            {
                                if (!txtQtd.Text.Equals(""))
                                {
                                    lblqtdRooms.Text = (Convert.ToInt32(txtQtd.Text) / 2).ToString();
                                }
                            }

                            break;

                        case "Triple":

                            if (!txtQtd.Text.Equals("") && Convert.ToInt32(txtQtd.Text) == 1)
                            {
                                lblqtdRooms.Text = txtQtd.Text;
                            }
                            else
                            {
                                if (!txtQtd.Text.Equals(""))
                                {
                                    lblqtdRooms.Text = (Convert.ToInt32(txtQtd.Text) / 3).ToString();
                                }
                            }

                            break;
                    }

                    //txtQtd.Focus();

                }

                ModalPopupExtenderGeraFile.Show();

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnAddSalvarFile_Click(object sender, EventArgs e)
        {
            try
            {
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                RangeDal rd = new RangeDal();
                FileFlightsDAL ffd = new FileFlightsDAL();

                QuoteTarifasDAL qtd = new QuoteTarifasDAL();
                QuoteTransDAL qtrfd = new QuoteTransDAL();
                QuoteServExtDAL qsexd = new QuoteServExtDAL();

                FileTarifasDAL ftd = new FileTarifasDAL();
                FileServExtraDAL fsed = new FileServExtraDAL();
                FileTransfersDAL ftrd = new FileTransfersDAL();

                int IdQuot = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));
                int IdFile = fcd.RetornaFile(txtQuoteNumber.Text);

                qtd.ExcluirPorFile(IdFile);
                qtrfd.ExcluirPorFile(IdFile);
                qsexd.ExcluirPorFile(IdFile);

                string de = "";
                string ate = "";

                foreach (GridViewRow item in GridColunasFile.Rows)
                {
                    RadioButton rdoSelectBase = (RadioButton)item.FindControl("rdoSelectBase");
                    if (rdoSelectBase.Checked)
                    {
                        de = item.Cells[1].Text;
                        ate = item.Cells[2].Text;
                        break;
                    }
                }

                Dictionary<string, int> rms = new Dictionary<string, int>();

                foreach (GridViewRow item in GridRooms.Rows)
                {
                    TextBox txtQtd = (TextBox)item.FindControl("txtQtd");

                    rms.Add(item.Cells[0].Text, Convert.ToInt32(txtQtd.Text));
                }

                foreach (Ranges item in rd.ObterPorTarifaDeAteOpt(IdQuot, de, ate, Convert.ToInt32(ViewState["QuoteAtiva"])))
                {

                    switch (item.Flag)
                    {
                        case "hotel":

                            File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(item.FileTabelaId));
                            Quote_Tarifas qt = new Quote_Tarifas();

                            //gera novo flight
                            if (ft.Flights_id != null)
                            {
                                File_Flights ff = ffd.ObterPorId(Convert.ToInt32(ft.Flights_id));
                                File_Flights fnew = new File_Flights();
                                fnew = ffd.Clone(ff, fnew);
                                ffd.Salvar(fnew);
                                qt.Flights_id = fnew.Flights_id;
                            }
                            else
                            {
                                qt.Flights_id = ft.Flights_id;
                            }


                            qt.File_id = IdFile;
                            //qt.Flights_id = ft.Flights_id;

                            if (ft.Room == null)
                            {
                                qt.Paxs = 1;
                                qt.Paying_Pax = 1;
                                qt.Supp_Paying_Pax = 1;
                            }
                            else
                            {
                                qt.Paxs = rms[ft.Room];
                                qt.Paying_Pax = rms[ft.Room];
                                qt.Supp_Paying_Pax = rms[ft.Room];
                            }

                            qt.Data_From = ft.Data_From;
                            qt.Data_To = ft.Data_To;

                            qt.markup = item.markup;
                            qt.markupNet = item.markupNet;
                            qt.desconto = item.desconto;
                            qt.descontoNet = item.descontoNet;
                            qt.S_merc_tarif_vendaNet = item.VendaNet;

                            qt.NumNoites = ft.NumNoites;
                            qt.Qtd_Tarifas = ft.Qtd_Tarifas;

                            qt.S_merc_tarif_valor = item.Valor;
                            qt.S_merc_tarif_venda = item.Venda;
                            qt.S_merc_tarif_total = item.ValorTotal;

                            qt.S_nome = ft.S_nome;
                            qt.S_email = ft.S_email;
                            qt.S_meal_nome = ft.S_meal_nome;
                            qt.S_meal_status = ft.S_meal_status;
                            qt.Meal = ft.Meal;
                            qt.S_meal_id = ft.S_meal_id;
                            qt.S_id = ft.S_id;
                            qt.Categoria = ft.Categoria;
                            qt.Categoria_id = ft.Categoria_id;

                            qt.Room = ft.Room;
                            qt.Room_id = ft.Room_id;

                            qt.Moeda = ft.Moeda;
                            qt.Moeda_id = ft.Moeda_id;
                            qt.Status = ft.Status;
                            qt.FTC = ft.FTC;
                            qt.Valor_Conferir = ft.Valor_Conferir;
                            qt.Cambio = ft.Cambio;
                            qt.Cancelado = ft.Cancelado;

                            qt.Flag = item.Flag;
                            qt.Ordem = item.Ordem;

                            qt.NomePacote = ft.NomePacote;
                            qt.UpdVenda = ft.UpdVenda;

                            qt.Range_id = item.Ranges_id; //ft.Range_id;

                            qt.GeraFile = ft.GeraFile;
                            qt.FdsFrom = ft.FdsFrom;
                            qt.FdsTo = ft.FdsTo;
                            qt.TBulk = ft.TBulk;
                            qt.TC = false;

                            qtd.Salvar(qt);

                            break;

                        case "servico":

                            File_Transfers ftrans = ftrd.ObterPorId(Convert.ToInt32(item.FileTabelaId));
                            Quote_Transf qr = new Quote_Transf();


                            //gera novo flight
                            if (ftrans.Flights_id != null)
                            {
                                File_Flights ff = ffd.ObterPorId(Convert.ToInt32(ftrans.Flights_id));
                                File_Flights fnew = new File_Flights();
                                fnew = ffd.Clone(ff, fnew);
                                ffd.Salvar(fnew);
                                qr.Flights_id = fnew.Flights_id;
                            }
                            else
                            {
                                qr.Flights_id = ftrans.Flights_id;
                            }

                            qr.File_id = IdFile;
                            //qr.Flights_id = ftrans.Flights_id;
                            qr.SubServico = ftrans.SubServico;

                            int qtdd = Convert.ToInt32(txtQtdPaxs.Text);

                            qr.Paxs = qtdd; //ftrans.Paxs;
                            qr.Paying_Pax = qtdd; //ftrans.Paying_Pax;
                            qr.Supp_Paying_Pax = qtdd; //ftrans.Supp_Paying_Pax;

                            qr.Data_From = ftrans.Data_From;
                            qr.Data_To = ftrans.Data_To;

                            qr.markup = item.markup;
                            qr.desconto = item.desconto;
                            qr.markupNet = item.markupNet;
                            qr.descontoNet = item.descontoNet;
                            qr.S_merc_tarif_vendaNet = item.VendaNet;

                            qr.Qtd_Transf = ftrans.Qtd_Transf;

                            qr.Transf_valor = item.Valor;
                            qr.Transf_vendaNet = item.VendaNet;
                            qr.Transf_venda = item.Venda;
                            qr.Transf_total = item.ValorTotal;

                            qr.Flag = item.Flag;
                            qr.S_nome = ftrans.S_nome;
                            qr.S_id = ftrans.S_id;
                            qr.Transf_nome = ftrans.Transf_nome;
                            qr.Transf_tipo = ftrans.Transf_tipo;
                            qr.Transf_tipo_categ = ftrans.Transf_tipo_categ;
                            qr.Moeda = ftrans.Moeda;
                            qr.Moeda_id = ftrans.Moeda_id;
                            qr.Trf_Tours = ftrans.Trf_Tours;
                            qr.Status = ftrans.Status;
                            qr.FTC = ftrans.FTC;
                            qr.Valor_Conferir = ftrans.Valor_Conferir;
                            qr.Cambio = ftrans.Cambio;
                            qr.Cancelado = ftrans.Cancelado;
                            qr.Ordem = ftrans.Ordem;
                            qr.UpdVenda = ftrans.UpdVenda;
                            qr.Trf_CID_id = ftrans.Trf_CID_id;

                            qr.Range_id = item.Ranges_id;

                            qr.TBulk = ftrans.TBulk;
                            qr.TC = false;

                            qtrfd.Salvar(qr);

                            break;

                        case "extra":

                            File_ServExtra fsex = fsed.ObterPorId(Convert.ToInt32(item.FileTabelaId));
                            Quote_ServExtra qs = new Quote_ServExtra();

                            //gera novo flight
                            if (fsex.Flights_id != null)
                            {
                                File_Flights ff = ffd.ObterPorId(Convert.ToInt32(fsex.Flights_id));
                                File_Flights fnew = new File_Flights();
                                fnew = ffd.Clone(ff, fnew);
                                ffd.Salvar(fnew);
                                qs.Flights_id = fnew.Flights_id;
                            }
                            else
                            {
                                qs.Flights_id = fsex.Flights_id;
                            }

                            qs.File_id = IdFile;
                            //qs.Flights_id = fsex.Flights_id;
                            qs.Paxs = fsex.Paxs;
                            qs.Paying_Pax = fsex.Paying_Pax;
                            qs.Supp_Paying_Pax = fsex.Supp_Paying_Pax;
                            qs.Data_From = fsex.Data_From;
                            qs.Data_To = fsex.Data_To;

                            qs.markup = item.markup;
                            qs.desconto = item.desconto;
                            qs.markupNet = item.markupNet;
                            qs.descontoNet = item.descontoNet;

                            qs.S_merc_tarif_vendaNet = item.VendaNet;

                            qs.Qtd_ServExtr = fsex.Qtd_ServExtr;

                            qs.File_ServExtra_valor = item.Valor;
                            qs.File_ServExtra_vendaNet = item.VendaNet;
                            qs.File_ServExtra_venda = item.Venda;
                            qs.File_ServExtra_total = item.ValorTotal;

                            qs.Flag = item.Flag;
                            qs.S_nome = fsex.S_nome;
                            qs.S_id = fsex.S_id;
                            qs.File_ServExtra_nome = fsex.File_ServExtra_nome;
                            qs.TipoServico = fsex.TipoServico;
                            qs.TipoServico_id = fsex.TipoServico_id;
                            qs.Moeda = fsex.Moeda;
                            qs.Moeda_id = fsex.Moeda_id;
                            qs.Status = fsex.Status;
                            qs.FTC = fsex.FTC;
                            qs.Valor_Conferir = fsex.Valor_Conferir;
                            qs.Cambio = fsex.Cambio;
                            qs.Cancelado = fsex.Cancelado;
                            qs.Ordem = fsex.Ordem;
                            qs.UpdVenda = fsex.UpdVenda;

                            qs.Range_id = item.Ranges_id;

                            qs.TBulk = fsex.TBulk;
                            qs.TC = false;

                            qsexd.Salvar(qs);

                            break;
                    }


                }


                foreach (Ranges item in rd.RetornaListaTCPBase(IdQuot, de, Convert.ToInt32(ViewState["QuoteAtiva"])))
                {

                    switch (item.Flag)
                    {
                        case "hotel":

                            File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(item.FileTabelaId));
                            Ranges r = rd.ObterPorIdID(Convert.ToInt32(item.RangeID));
                            Quote_Tarifas qt = new Quote_Tarifas();


                            //gera novo flight
                            if (ft.Flights_id != null)
                            {
                                File_Flights ff = ffd.ObterPorId(Convert.ToInt32(ft.Flights_id));
                                File_Flights fnew = new File_Flights();
                                fnew = ffd.Clone(ff, fnew);
                                ffd.Salvar(fnew);
                                qt.Flights_id = fnew.Flights_id;
                            }
                            else
                            {
                                qt.Flights_id = ft.Flights_id;
                            }


                            qt.File_id = IdFile;
                            //qt.Flights_id = ft.Flights_id;

                            qt.Paxs = r.QtdTC; //rms[ft.Room]; //ft.Paxs;
                            qt.Paying_Pax = r.QtdTC; //rms[ft.Room]; //ft.Paying_Pax;
                            qt.Supp_Paying_Pax = r.QtdTC; //rms[ft.Room]; //ft.Supp_Paying_Pax;

                            qt.Data_From = ft.Data_From;
                            qt.Data_To = ft.Data_To;

                            qt.markup = item.markup;
                            qt.markupNet = item.markupNet;
                            qt.desconto = item.desconto;
                            qt.descontoNet = item.descontoNet;
                            qt.S_merc_tarif_vendaNet = item.VendaNet;

                            qt.NumNoites = ft.NumNoites;
                            qt.Qtd_Tarifas = ft.Qtd_Tarifas;

                            qt.S_merc_tarif_valor = item.Valor;
                            qt.S_merc_tarif_venda = item.Venda;
                            qt.S_merc_tarif_total = item.ValorTotal;

                            qt.S_nome = ft.S_nome;
                            qt.S_email = ft.S_email;
                            qt.S_meal_nome = ft.S_meal_nome;
                            qt.S_meal_status = ft.S_meal_status;
                            qt.Meal = ft.Meal;
                            qt.S_meal_id = ft.S_meal_id;
                            qt.S_id = ft.S_id;
                            qt.Categoria = ft.Categoria;
                            qt.Categoria_id = ft.Categoria_id;

                            qt.Room = ft.Room;
                            qt.Room_id = ft.Room_id;

                            qt.Moeda = ft.Moeda;
                            qt.Moeda_id = ft.Moeda_id;
                            qt.Status = ft.Status;
                            qt.FTC = ft.FTC;
                            qt.Valor_Conferir = ft.Valor_Conferir;
                            qt.Cambio = ft.Cambio;
                            qt.Cancelado = ft.Cancelado;

                            qt.Flag = item.Flag;
                            qt.Ordem = item.Ordem;

                            qt.NomePacote = ft.NomePacote;
                            qt.UpdVenda = ft.UpdVenda;

                            qt.Range_id = item.RangeID; //ft.Range_id;

                            qt.GeraFile = ft.GeraFile;
                            qt.FdsFrom = ft.FdsFrom;
                            qt.FdsTo = ft.FdsTo;
                            qt.TBulk = ft.TBulk;
                            qt.TC = true;

                            qtd.Salvar(qt);

                            break;

                        case "servico":

                            File_Transfers ftrans = ftrd.ObterPorId(Convert.ToInt32(item.FileTabelaId));
                            Ranges r2 = rd.ObterPorIdID(Convert.ToInt32(item.RangeID));
                            Quote_Transf qr = new Quote_Transf();

                            //gera novo flight
                            if (ftrans.Flights_id != null)
                            {
                                File_Flights ff = ffd.ObterPorId(Convert.ToInt32(ftrans.Flights_id));
                                File_Flights fnew = new File_Flights();
                                fnew = ffd.Clone(ff, fnew);
                                ffd.Salvar(fnew);
                                qr.Flights_id = fnew.Flights_id;
                            }
                            else
                            {
                                qr.Flights_id = ftrans.Flights_id;
                            }

                            qr.File_id = IdFile;
                            //qr.Flights_id = ftrans.Flights_id;
                            qr.SubServico = ftrans.SubServico;

                            int qtdd = Convert.ToInt32(txtQtdPaxs.Text);

                            qr.Paxs = r2.QtdTC; //qtdd; //ftrans.Paxs;
                            qr.Paying_Pax = r2.QtdTC; //qtdd; //ftrans.Paying_Pax;
                            qr.Supp_Paying_Pax = r2.QtdTC; //qtdd; //ftrans.Supp_Paying_Pax;

                            qr.Data_From = ftrans.Data_From;
                            qr.Data_To = ftrans.Data_To;

                            qr.markup = item.markup;
                            qr.desconto = item.desconto;
                            qr.markupNet = item.markupNet;
                            qr.descontoNet = item.descontoNet;
                            qr.S_merc_tarif_vendaNet = item.VendaNet;

                            qr.Qtd_Transf = ftrans.Qtd_Transf;

                            qr.Transf_valor = item.Valor;
                            qr.Transf_vendaNet = item.VendaNet;
                            qr.Transf_venda = item.Venda;
                            qr.Transf_total = item.ValorTotal;

                            qr.Flag = item.Flag;
                            qr.S_nome = ftrans.S_nome;
                            qr.S_id = ftrans.S_id;
                            qr.Transf_nome = ftrans.Transf_nome;
                            qr.Transf_tipo = ftrans.Transf_tipo;
                            qr.Transf_tipo_categ = ftrans.Transf_tipo_categ;
                            qr.Moeda = ftrans.Moeda;
                            qr.Moeda_id = ftrans.Moeda_id;
                            qr.Trf_Tours = ftrans.Trf_Tours;
                            qr.Status = ftrans.Status;
                            qr.FTC = ftrans.FTC;
                            qr.Valor_Conferir = ftrans.Valor_Conferir;
                            qr.Cambio = ftrans.Cambio;
                            qr.Cancelado = ftrans.Cancelado;
                            qr.Ordem = ftrans.Ordem;
                            qr.UpdVenda = ftrans.UpdVenda;
                            qr.Trf_CID_id = ftrans.Trf_CID_id;

                            qr.Range_id = item.RangeID;

                            qr.TBulk = ftrans.TBulk;
                            qr.TC = true;

                            qtrfd.Salvar(qr);

                            break;

                        case "extra":

                            File_ServExtra fsex = fsed.ObterPorId(Convert.ToInt32(item.FileTabelaId));
                            Ranges r3 = rd.ObterPorIdID(Convert.ToInt32(item.RangeID));
                            Quote_ServExtra qs = new Quote_ServExtra();

                            //gera novo flight
                            if (fsex.Flights_id != null)
                            {
                                File_Flights ff = ffd.ObterPorId(Convert.ToInt32(fsex.Flights_id));
                                File_Flights fnew = new File_Flights();
                                fnew = ffd.Clone(ff, fnew);
                                ffd.Salvar(fnew);
                                qs.Flights_id = fnew.Flights_id;
                            }
                            else
                            {
                                qs.Flights_id = fsex.Flights_id;
                            }

                            qs.File_id = IdFile;
                            //qs.Flights_id = fsex.Flights_id;

                            qs.Paxs = r3.QtdTC; //fsex.Paxs;
                            qs.Paying_Pax = r3.QtdTC; //fsex.Paying_Pax;
                            qs.Supp_Paying_Pax = r3.QtdTC; //fsex.Supp_Paying_Pax;

                            qs.Data_From = fsex.Data_From;
                            qs.Data_To = fsex.Data_To;

                            qs.markup = item.markup;
                            qs.desconto = item.desconto;
                            qs.markupNet = item.markupNet;
                            qs.descontoNet = item.descontoNet;

                            qs.S_merc_tarif_vendaNet = item.VendaNet;

                            qs.Qtd_ServExtr = fsex.Qtd_ServExtr;

                            qs.File_ServExtra_valor = item.Valor;
                            qs.File_ServExtra_vendaNet = item.VendaNet;
                            qs.File_ServExtra_venda = item.Venda;
                            qs.File_ServExtra_total = item.ValorTotal;

                            qs.Flag = item.Flag;
                            qs.S_nome = fsex.S_nome;
                            qs.S_id = fsex.S_id;
                            qs.File_ServExtra_nome = fsex.File_ServExtra_nome;
                            qs.TipoServico = fsex.TipoServico;
                            qs.TipoServico_id = fsex.TipoServico_id;
                            qs.Moeda = fsex.Moeda;
                            qs.Moeda_id = fsex.Moeda_id;
                            qs.Status = fsex.Status;
                            qs.FTC = fsex.FTC;
                            qs.Valor_Conferir = fsex.Valor_Conferir;
                            qs.Cambio = fsex.Cambio;
                            qs.Cancelado = fsex.Cancelado;
                            qs.Ordem = fsex.Ordem;
                            qs.UpdVenda = fsex.UpdVenda;

                            qs.Range_id = item.RangeID;

                            qs.TBulk = fsex.TBulk;
                            qs.TC = true;

                            qsexd.Salvar(qs);

                            break;
                    }
                }

                txtQtdPaxs.Text = "";

                PopularNewFile();

                MostrarMsg("File gerado com sucesso.");

                //string script = "function MudaTab() {";
                //script = script + "$('#tabs').tabs('select', '#tabs-2');}";
                //ScriptManager.RegisterStartupScript(this, this.GetType(), "Infos", script, true);                

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void PopularNewFile()
        {
            try
            {
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                int IdFile = fcd.RetornaFile(txtQuoteNumber.Text);

                GridBasesTarifasNewFile.DataSource = fcd.MontaCarrinhoNewFileFinal(IdFile);
                GridBasesTarifasNewFile.DataBind();

                GridNewFile(GridBasesTarifasNewFile);
                PopulaTotalNewFile();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void GridNewFile(GridView grid)
        {
            try
            {
                QuoteTarifasDAL qtd = new QuoteTarifasDAL();
                QuoteTransDAL qtr = new QuoteTransDAL();
                QuoteServExtDAL qsed = new QuoteServExtDAL();


                if (grid.Rows.Count == 0)
                {
                    return;
                }

                foreach (GridViewRow item in grid.Rows)
                {
                    ImageButton imgFlights = (ImageButton)item.FindControl("imgFlights");
                    Label lblRoom = (Label)item.FindControl("lblRoom");
                    Label lblCategoria = (Label)item.FindControl("lblCategoria");
                    Label lblFlag = (Label)item.FindControl("lblFlag");
                    Label lblIdRetorna = (Label)item.FindControl("lblIdRetorna");
                    Label lblCidade = (Label)item.FindControl("lblCidade");
                    Label lblCidadeIata = (Label)item.FindControl("lblCidadeIata");
                    Label lblNomeSupplier = (Label)item.FindControl("lblNomeSupplier");
                    Label lblStatus = (Label)item.FindControl("lblStatus");
                    Label lblBulk = (Label)item.FindControl("lblBulk");
                    ImageButton imgBulk = (ImageButton)item.FindControl("imgBulk");
                    ImageButton imgStatus = (ImageButton)item.FindControl("imgStatus");

                    CidadeDAL cdl = new CidadeDAL();

                    if (lblStatus.Text.Equals("OR"))
                    {
                        imgStatus.ImageUrl = "~/images/Icones/OnRequest.bmp";
                    }
                    else
                    {
                        imgStatus.ImageUrl = "~/images/Icones/Confirm.bmp";
                    }

                    if (lblBulk.Text.Equals("False") || lblBulk.Text.Equals(""))
                    {
                        imgBulk.ImageUrl = "~/images/minus-small.png";
                    }
                    else
                    {
                        imgBulk.ImageUrl = "~/images/valid.gif";
                    }

                    switch (lblFlag.Text)
                    {
                        case "hotel":

                            Quote_Tarifas qt = qtd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));

                            Cidade chotel = cdl.ObterPorNomeSupplier(qt.S_nome);

                            if (qt.S_meal_nome == null)
                            {
                                lblNomeSupplier.Text = qt.S_nome;
                            }
                            else
                            {
                                lblNomeSupplier.Text = qt.S_nome + " - " + qt.S_meal_nome;
                            }

                            lblCidade.Text = chotel.CID_nome;
                            lblCidadeIata.Text = chotel.CID_cod_Iata;

                            if (qtd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text)).Flights_id == null)
                            {
                                imgFlights.ImageUrl = "~/images/Icones/flightsS.png";
                            }
                            else
                            {
                                imgFlights.ImageUrl = "~/images/Icones/flights.png";
                            }

                            break;

                        case "servico":

                            Quote_Transf qtra = qtr.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));

                            lblNomeSupplier.Text = qtra.Transf_nome;

                            Cidade cserv = cdl.ObterPorNomeServico(qtra.Transf_nome);

                            lblCidade.Text = cserv.CID_nome;
                            lblCidadeIata.Text = cserv.CID_cod_Iata;

                            if (qtr.ObterPorId(Convert.ToInt32(lblIdRetorna.Text)).Flights_id == null)
                            {
                                imgFlights.ImageUrl = "~/images/Icones/flightsS.png";
                            }
                            else
                            {
                                imgFlights.ImageUrl = "~/images/Icones/flights.png";
                            }

                            break;
                        case "extra":

                            Quote_ServExtra fsext = qsed.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));

                            lblNomeSupplier.Text = fsext.File_ServExtra_nome;

                            Cidade cservextra = cdl.ObterPorNomeSupplier(fsext.S_nome);

                            lblCidade.Text = cservextra.CID_nome;
                            lblCidadeIata.Text = cservextra.CID_cod_Iata;

                            if (qsed.ObterPorId(Convert.ToInt32(lblIdRetorna.Text)).Flights_id == null)
                            {
                                imgFlights.ImageUrl = "~/images/Icones/flightsS.png";
                            }
                            else
                            {
                                imgFlights.ImageUrl = "~/images/Icones/flights.png";
                            }

                            break;
                    }

                }


                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                int IdQuote = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));
                int IdFile = fcd.RetornaFile(txtQuoteNumber.Text);

                foreach (GridViewRow item2 in grid.Rows)
                {
                    Label lblIdRetorna = (Label)item2.FindControl("lblIdRetorna");
                    Label lblFlag = (Label)item2.FindControl("lblFlag");
                    Label lblNomeStatus = (Label)item2.FindControl("lblNomeStatus");
                    LinkButton lnkValorTotalHotel8 = (LinkButton)item2.FindControl("lnkValorTotalHotel8");
                    LinkButton lnkValorTotalHotel10 = (LinkButton)item2.FindControl("lnkValorTotalHotel10");
                    Label lblValorTotalHotel10 = (Label)item2.FindControl("lblValorTotalHotel10");

                    switch (lblFlag.Text)
                    {
                        case "hotel":

                            Quote_Tarifas qt = qtd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));

                            if (!lblNomeStatus.Text.Equals(""))
                            {
                                lnkValorTotalHotel8.Text = qt.S_meal_status; //new QuoteTarifasDAL().ObterPorId(Convert.ToInt32(lblIdRetorna.Text)).S_meal_status;
                                lblValorTotalHotel10.Text = "0,00";
                            }
                            else
                            {
                                lnkValorTotalHotel8.Text = qt.S_merc_tarif_total.ToString(); //new QuoteTarifasDAL().ObterPorId(Convert.ToInt32(lblIdRetorna.Text)).S_merc_tarif_total.ToString();
                                lblValorTotalHotel10.Text = Convert.ToDecimal(qt.S_merc_tarif_total * qt.Paying_Pax).ToString();
                            }
                            break;

                        case "servico":

                            Quote_Transf qtrr = qtr.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));

                            lnkValorTotalHotel8.Text = qtrr.Transf_total.ToString(); //new QuoteTransDAL().ObterPorId(Convert.ToInt32(lblIdRetorna.Text)).Transf_total.ToString();
                            lblValorTotalHotel10.Text = Convert.ToDecimal(qtrr.Transf_total * qtrr.Paying_Pax).ToString();
                            break;

                        case "extra":

                            Quote_ServExtra qs = qsed.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));

                            lnkValorTotalHotel8.Text = qs.File_ServExtra_total.ToString(); //new QuoteServExtDAL().ObterPorId(Convert.ToInt32(lblIdRetorna.Text)).File_ServExtra_total.ToString();
                            lblValorTotalHotel10.Text = Convert.ToDecimal(qs.File_ServExtra_total * qs.Paying_Pax).ToString();
                            break;
                    }
                }

                if (fcd.VerificaExisteTCQuotes(IdFile))
                {
                    GridBasesTarifasNewFile.Columns[9].Visible = true;
                    GridBasesTarifasNewFile.HeaderRow.Cells[9].Text = "TC";

                    int i = 1;
                    int j = 1;
                    int k = 1;

                    foreach (GridViewRow item2 in grid.Rows)
                    {
                        Label lblFlag = (Label)item2.FindControl("lblFlag");
                        Label lblIdTarifaTC = (Label)item2.FindControl("lblIdTarifaTC");
                        LinkButton lnkValorTotalHotel10 = (LinkButton)item2.FindControl("lnkValorTotalHotel10");
                        Label lblValorTotalHotel10 = (Label)item2.FindControl("lblValorTotalHotel10");

                        LinkButton lnkValorTotalHotel9 = (LinkButton)item2.FindControl("lnkValorTotalHotel9");

                        switch (lblFlag.Text)
                        {
                            case "hotel":

                                Quote_Tarifas qt = qtd.ObterTC(IdFile, i);

                                if (qt.S_meal_status == null)
                                {
                                    lnkValorTotalHotel9.Text = qt.S_merc_tarif_total.ToString();
                                    lblIdTarifaTC.Text = qt.Quote_Tarifas_id.ToString();
                                    decimal totalqt = Convert.ToDecimal(qt.S_merc_tarif_total * qt.Paying_Pax);

                                    lblValorTotalHotel10.Text = (Convert.ToDecimal(lblValorTotalHotel10.Text) + totalqt).ToString();
                                }
                                else
                                {
                                    lnkValorTotalHotel9.Text = qt.S_meal_status;
                                    lblIdTarifaTC.Text = qt.Quote_Tarifas_id.ToString();
                                }

                                i++;
                                break;

                            case "servico":

                                Quote_Transf qtrr = qtr.ObterTC(IdFile, j);

                                lnkValorTotalHotel9.Text = qtrr.Transf_total.ToString();
                                lblIdTarifaTC.Text = qtrr.Quote_Transf_id.ToString();

                                decimal totalqtrr = Convert.ToDecimal(qtrr.Transf_total * qtrr.Paying_Pax);

                                lblValorTotalHotel10.Text = (Convert.ToDecimal(lblValorTotalHotel10.Text) + totalqtrr).ToString();

                                j++;
                                break;

                            case "extra":

                                Quote_ServExtra qse = qsed.ObterTC(IdFile, k);

                                lnkValorTotalHotel9.Text = qse.File_ServExtra_total.ToString();
                                lblIdTarifaTC.Text = qse.Quote_ServExtra_id.ToString();

                                decimal totalqse = Convert.ToDecimal(qse.File_ServExtra_total * qse.Paying_Pax);

                                lblValorTotalHotel10.Text = (Convert.ToDecimal(lblValorTotalHotel10.Text) + totalqse).ToString();

                                k++;
                                break;
                        }


                    }

                }

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void PopulaTotalNewFile()
        {
            try
            {

                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                int IdFile = fcd.RetornaFile(txtQuoteNumber.Text);

                DataTable dummy = new DataTable();
                dummy.Columns.Add("total");
                dummy.Columns.Add("room");

                List<TotalFileModel> lista = fcd.ValoresTotaisFile(IdFile);

                int qtdrooms = lista.Where(l => !l.room.Equals("")).Count();
                string[] rooms = new string[qtdrooms];
                int cont = 0;

                foreach (var roomsrow in lista)
                {
                    if (!roomsrow.room.Equals(""))
                    {
                        rooms[cont] = roomsrow.room;
                        cont++;
                    }
                }

                cont = 0;
                decimal total = 0;

                for (int i = 0; i < qtdrooms; i++)
                {
                    DataRow drow = dummy.NewRow();

                    foreach (var item in lista)
                    {
                        if (item.room.Equals(rooms[i]))
                        {
                            total = total + item.total;
                        }
                        else if (item.room.Equals(""))
                        {
                            total = total + item.total;
                        }
                    }

                    drow["total"] = total.ToString();
                    drow["room"] = rooms[i];

                    dummy.Rows.Add(drow);
                    total = 0;
                }

                DataListRates.DataSource = dummy;
                DataListRates.RepeatColumns = qtdrooms;
                DataListRates.DataBind();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void TarifasGridNewFile_Command(object sender, CommandEventArgs e)
        {
            try
            {
                ViewState["TarifaFile"] = 1;

                string[] pars = e.CommandArgument.ToString().Split(',');

                int IdFTarifas = Convert.ToInt32(pars[1]);
                int col = Convert.ToInt32(pars[0]);

                string[] titulo = GridBasesTarifasNewFile.HeaderRow.Cells[col].Text.ToString().Split('/');
                int IdTarifaTc = 0;

                if (titulo[0].Equals("TC"))
                {
                    foreach (GridViewRow item in GridBasesTarifasNewFile.Rows)
                    {
                        if (item.DataItemIndex == Convert.ToInt32(pars[3]))
                        {
                            Label lblIdTarifaTC = (Label)item.FindControl("lblIdTarifaTC");
                            IdTarifaTc = Convert.ToInt32(lblIdTarifaTC.Text);
                            ViewState["IdFTarifasBasesNewFile"] = IdTarifaTc;
                            break;
                        }
                    }
                }
                else
                {
                    ViewState["IdFTarifasBasesNewFile"] = IdFTarifas;
                }

                if (pars[3].ToString().Equals("True"))
                {
                    imgEditSubServico.Visible = true;
                    ViewState["DadosOpenSubServicos"] = e.CommandArgument.ToString();
                }
                else
                {
                    imgEditSubServico.Visible = false;
                }

                int tot = 0;

                switch (pars[2].ToString())
                {
                    case "hotel":

                        QuoteTarifasDAL ftd = new QuoteTarifasDAL();
                        Quote_Tarifas ft;

                        if (IdTarifaTc == 0) ft = ftd.ObterPorId(IdFTarifas); else ft = ftd.ObterPorId(IdTarifaTc);

                        //txtPaxsTarifas.Text = ft.Paying_Pax.ToString();

                        txtPaxsTarifas.Text = ft.Paying_Pax.ToString();
                        txtSupplierPayPaxs.Text = ft.Supp_Paying_Pax.ToString();
                        txtPaxs.Text = ft.Paxs.ToString();

                        txtNetNetTarifas.Text = ft.S_merc_tarif_valor.ToString();
                        txtNetTarifas.Text = ft.S_merc_tarif_vendaNet.ToString();
                        txtMarkupTarifas.Text = ft.markup.ToString();
                        txtMarkupNetTarifas.Text = ft.markupNet.ToString();
                        txtDescontoTarifas.Text = ft.desconto.ToString();
                        txtDescontoNetTarifas.Text = ft.descontoNet.ToString();
                        txtVendaTarifas.Text = ft.S_merc_tarif_venda.ToString();

                        decimal total = Convert.ToDecimal(ft.S_merc_tarif_total * ft.Paying_Pax);

                        lblQtdNoitesPopUp.Text = "x" + (Convert.ToDateTime(ft.Data_To) - Convert.ToDateTime(ft.Data_From)).Days.ToString() + " Noites.";

                        lbltotalTarifas.Text = total.ToString();

                        break;

                    case "servico":

                        QuoteTransDAL ftrd = new QuoteTransDAL();
                        Quote_Transf ftr;

                        if (IdTarifaTc == 0) ftr = ftrd.ObterPorId(IdFTarifas); else ftr = ftrd.ObterPorId(IdTarifaTc);

                        txtPaxsTarifas.Text = ftr.Paying_Pax.ToString();
                        txtSupplierPayPaxs.Text = ftr.Supp_Paying_Pax.ToString();
                        txtPaxs.Text = ftr.Paxs.ToString();

                        //txtPaxsTarifas.Text = ftr.Paying_Pax.ToString();

                        txtNetNetTarifas.Text = ftr.Transf_valor.ToString();
                        txtNetTarifas.Text = ftr.Transf_vendaNet.ToString();
                        txtMarkupTarifas.Text = ftr.markup.ToString();
                        txtMarkupNetTarifas.Text = ftr.markupNet.ToString();
                        txtDescontoTarifas.Text = ftr.desconto.ToString();
                        txtDescontoNetTarifas.Text = ftr.descontoNet.ToString();
                        txtVendaTarifas.Text = ftr.Transf_venda.ToString();

                        decimal total2 = Convert.ToDecimal(ftr.Transf_total * ftr.Paying_Pax);

                        lbltotalTarifas.Text = total2.ToString();

                        break;

                    case "extra":

                        QuoteServExtDAL fsvd = new QuoteServExtDAL();
                        Quote_ServExtra ftserv;

                        if (IdTarifaTc == 0) ftserv = fsvd.ObterPorId(IdFTarifas); else ftserv = fsvd.ObterPorId(IdTarifaTc);

                        txtPaxsTarifas.Text = ftserv.Paying_Pax.ToString();
                        txtSupplierPayPaxs.Text = ftserv.Supp_Paying_Pax.ToString();
                        txtPaxs.Text = ftserv.Paxs.ToString();

                        //txtPaxsTarifas.Text = ftserv.Paying_Pax.ToString();

                        txtNetNetTarifas.Text = ftserv.File_ServExtra_valor.ToString();
                        txtNetTarifas.Text = ftserv.File_ServExtra_vendaNet.ToString();
                        txtMarkupTarifas.Text = ftserv.markup.ToString();
                        txtMarkupNetTarifas.Text = ftserv.markupNet.ToString();
                        txtDescontoTarifas.Text = ftserv.desconto.ToString();
                        txtDescontoNetTarifas.Text = ftserv.descontoNet.ToString();
                        txtVendaTarifas.Text = ftserv.File_ServExtra_venda.ToString();

                        decimal total3 = Convert.ToDecimal(ftserv.File_ServExtra_total * ftserv.Paying_Pax);

                        lbltotalTarifas.Text = total3.ToString();

                        break;

                }

                ViewState["FlagTarifaClicadaNewFile"] = pars[2].ToString() + "," + col;

                ModalPopupExtenderTarifasGrids.Show();

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void ExluirFileCarrinhoTarifasNew(object sender, CommandEventArgs e)
        {
            try
            {
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                string[] pars = e.CommandArgument.ToString().Split(',');

                int idretorna = Convert.ToInt32(pars[0]);
                string flag = pars[1];
                int IdQuot = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));

                switch (flag)
                {
                    case "hotel":

                        QuoteTarifasDAL qtd = new QuoteTarifasDAL();
                        List<Quote_Tarifas> lqf = qtd.ObterPorIdTC(Convert.ToInt32(qtd.ObterPorId(idretorna).Range_id));
                        qtd.ExcluirLista(lqf);

                        break;

                    case "servico":

                        QuoteTransDAL qtrd = new QuoteTransDAL();
                        List<Quote_Transf> lqt = qtrd.ObterPorIdTC(Convert.ToInt32(qtrd.ObterPorId(idretorna).Range_id));
                        qtrd.ExcluirLista(lqt);

                        break;

                    case "extra":

                        QuoteServExtDAL qsd = new QuoteServExtDAL();
                        List<Quote_ServExtra> lqs = qsd.ObterPorIdTC(Convert.ToInt32(qsd.ObterPorId(idretorna).Range_id));
                        qsd.ExcluirLista(lqs);

                        break;
                }

                PopularNewFile();

                MostrarMsg("Registro excluído com sucesso.");

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        #endregion

        #region Files Transfers Carrinho

        protected void btnSearchTransfers_Click(object sender, EventArgs e)
        {
            PopulaDataLisTransfers();
            PopulaDataLisTransfersSubServicos();
        }

        protected void BtnAddTranfersFile(object sender, CommandEventArgs e)
        {
            if (rdoOptFileTranfers.SelectedValue.Equals("0"))
            {
                btnAddTransferFileNew(Convert.ToInt32(e.CommandArgument));
            }
            else
            {
                btnAddTransferFileNewDirFile(Convert.ToInt32(e.CommandArgument));
            }
            //btnAddTransferFile_Click(sender, e);
        }

        protected void btnAddTransferFile_Click(object sender, CommandEventArgs e)
        {
            try
            {

                FileTransfersDAL ftd = new FileTransfersDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                ClienteDAL cli = new ClienteDAL();

                HolidaysDAL hdal = new HolidaysDAL();
                HolidaysDatesDAL hdatesdal = new HolidaysDatesDAL();

                ClienteMarkupDAL climark = new ClienteMarkupDAL();

                //decimal markupcliente = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_servico);
                //decimal markupdesconto = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_descontoServico);

                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToDateTime(txtDataFromTrans.Text));
                decimal markupcliente = 0, markupdesconto = 0;
                if (mkfile != null)
                {
                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                    markupdesconto = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                }
                else
                {
                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(Convert.ToDateTime(txtDataFromTrans.Text));

                    if (mgfile != null)
                    {
                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                        markupdesconto = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                    }
                    else
                    {
                        MostrarMsg("Não existe Markup cadastrado.");
                        return;
                    }
                }

                if (fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])) == null)
                {
                    File_Carrinho fc = new File_Carrinho();

                    fc.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                    fcd.Salvar(fc);
                }

                foreach (DataListItem item in DataListTransfers.Items)
                {

                    if (item.ItemIndex == Convert.ToInt32(e.CommandArgument))
                    {
                        //btnAddTransferFileNew(Convert.ToInt32(e.CommandArgument));

                        Label lblTituloTransfer = (Label)item.FindControl("lblTituloTransfer");
                        Label lblSupplierNome = (Label)item.FindControl("lblSupplierNome");
                        Label lblTarifaTotal = (Label)item.FindControl("lblTarifaTotal");
                        Label lblMoeda0 = (Label)item.FindControl("lblMoeda0");
                        Label lblMoedaId = (Label)item.FindControl("lblMoedaId");
                        Label lblSuplID = (Label)item.FindControl("lblSuplID");

                        File_Transfers ft = new File_Transfers();
                        MoedaDAL mod = new MoedaDAL();
                        CambioDAL cambDal = new CambioDAL();

                        ServicoDAL servd = new ServicoDAL();
                        S_Servicos ss = servd.ObterPorNome(lblTituloTransfer.Text);

                        if (hdal.VerificaHoliday(Convert.ToDateTime(txtDataFromTrans.Text), ss.Servicos_Id) ||
                            hdal.VerificaHolidayEntreDatas(Convert.ToDateTime(txtDataFromTrans.Text), ss.Servicos_Id) ||
                            hdal.VerificaHolidaySemana(Convert.ToDateTime(txtDataFromTrans.Text), ss.Servicos_Id))
                        {
                            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "AlertarHolidays()", true);
                            return;
                        }

                        if (lblMoedaId.Text != ddlMoeda.SelectedValue)
                        {
                            Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(lblMoedaId.Text), Convert.ToInt32(ddlMoeda.SelectedValue));

                            decimal valor = Convert.ToDecimal(lblTarifaTotal.Text);

                            decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                            ft.Transf_valor = valorComCambio;
                        }
                        else
                        {
                            ft.Transf_valor = Convert.ToDecimal(lblTarifaTotal.Text);
                        }

                        ft.Trf_CID_id = ObterIdCidadeServico(lblTituloTransfer.Text); //Convert.ToInt32(ddlCidadeTransFiltro.SelectedValue);

                        ft.Paxs = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);
                        ft.Paying_Pax = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);
                        ft.Supp_Paying_Pax = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);

                        int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                        ft.Ordem = Ordem;

                        ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                        ft.S_nome = lblSupplierNome.Text;
                        ft.Transf_nome = lblTituloTransfer.Text;
                        //ft.Moeda = lblMoeda0.Text;
                        ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;
                        ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);


                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        {

                            SupplierDAL sd = new SupplierDAL();
                            MarkupPaisDAL mkd = new MarkupPaisDAL();

                            Supplier spp = sd.ObterPorId(Convert.ToInt32(lblSuplID.Text));
                            MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                            ft.markup = mkp.MarkupServ;
                            ft.desconto = mkp.Desconto;
                            ft.markupNet = markupcliente;
                            ft.descontoNet = markupdesconto;
                        }
                        else
                        {
                            ft.markup = markupcliente;
                            ft.desconto = markupdesconto;
                            ft.markupNet = 0;
                            ft.descontoNet = 0;
                        }

                        //ft.markup = markupcliente;
                        //ft.desconto = markupdesconto;

                        //ft.Transf_valor = Convert.ToDecimal(lblTarifaTotal.Text);
                        ft.Qtd_Transf = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);
                        ft.Data_From = Convert.ToDateTime(txtDataFromTrans.Text);
                        ft.Data_To = Convert.ToDateTime(txtDataToTrans.Text);
                        ft.Trf_Tours = "TRF";
                        ft.Status = "OR";
                        ft.S_id = Convert.ToInt32(lblSuplID.Text);
                        ft.FTC = false;

                        ftd.Salvar(ft);
                    }
                }

                PopularGridListCarrinhoTransfers(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                CalculaValorTotal();
                MostrarMsg("Transfer adicionado ao file com sucesso.");

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void btnAddTransferFileNew(int e)
        {
            try
            {

                FileTransfersDAL ftd = new FileTransfersDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                ClienteDAL cli = new ClienteDAL();
                RangeDal rd = new RangeDal();
                CidadeDAL cdal = new CidadeDAL();
                ServicoDAL sd = new ServicoDAL();

                File_Carrinho fcarr = fcd.RetornaFileObj(txtQuoteNumber.Text);

                if (fcarr != null)
                {
                    if (rd.ListarTodosGroup(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text))).Count() == 0)
                    {
                        if (txtBaseDeNew.Text.Equals("") || txtBaseAteNew.Text.Equals(""))
                        {
                            MostrarMsg("Selecione uma base inicial para o file.");
                            return;
                        }
                    }
                }

                ClienteMarkupDAL climark = new ClienteMarkupDAL();

                //decimal markupcliente = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_servico);
                //decimal markupdesconto = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_descontoServico);

                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToDateTime(txtDataFromTrans.Text));
                decimal markupcliente = 0, markupdesconto = 0;
                if (mkfile != null)
                {
                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                    markupdesconto = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                }
                else
                {
                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(Convert.ToDateTime(txtDataFromTrans.Text));

                    if (mgfile != null)
                    {
                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                        markupdesconto = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                    }
                    else
                    {
                        MostrarMsg("Não existe Markup cadastrado.");
                        return;
                    }
                }

                if (fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])) == null)
                {
                    File_Carrinho fc = new File_Carrinho();

                    fc.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                    fcd.Salvar(fc);
                }

                foreach (DataListItem item in DataListTransfers.Items)
                {

                    if (item.ItemIndex == e)
                    {

                        Label lblTituloTransfer = (Label)item.FindControl("lblTituloTransfer");
                        Label lblSupplierNome = (Label)item.FindControl("lblSupplierNome");
                        Label lblTarifaTotal = (Label)item.FindControl("lblTarifaTotal");
                        Label lblMoeda0 = (Label)item.FindControl("lblMoeda0");
                        Label lblMoedaId = (Label)item.FindControl("lblMoedaId");
                        Label lblSuplID = (Label)item.FindControl("lblSuplID");


                        File_Transfers ft = new File_Transfers();
                        MoedaDAL mod = new MoedaDAL();
                        CambioDAL cambDal = new CambioDAL();


                        //ft.Trf_CID_id = ObterIdCidadeServico(lblTituloTransfer.Text); //Convert.ToInt32(ddlCidadeTransFiltro.SelectedValue);

                        if (cdal.ObterPorNome(txtAutoCidadeTransfer.Text) != null)
                        {
                            ft.Trf_CID_id = cdal.ObterPorNome(txtAutoCidadeTransfer.Text).CID_id;
                        }
                        else
                        {
                            if (sd.ObterPorNomeLista(lblTituloTransfer.Text).Count > 1)
                            {
                                Supplier suppp = new SupplierDAL().ObterSupplierPorNome(lblSupplierNome.Text);
                                if (suppp != null)
                                {
                                    ft.Trf_CID_id = suppp.CID_id;
                                }
                            }
                        }

                        ft.Paxs = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);
                        ft.Paying_Pax = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);
                        ft.Supp_Paying_Pax = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);

                        int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                        ft.Ordem = Ordem;

                        ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                        ft.S_nome = lblSupplierNome.Text;
                        ft.Transf_nome = lblTituloTransfer.Text;
                        ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;
                        ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);


                        ft.Qtd_Transf = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);
                        ft.Data_From = Convert.ToDateTime(txtDataFromTrans.Text);
                        ft.Data_To = Convert.ToDateTime(txtDataToTrans.Text);
                        ft.Trf_Tours = "TRF";
                        ft.Status = "OR";
                        ft.S_id = Convert.ToInt32(lblSuplID.Text);
                        ft.FTC = false;

                        ft.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                        ftd.Salvar(ft);

                        File_Transfers ftrange = new File_Transfers();
                        ftrange.Range_id = 0;
                        ftrange.File_Transf_id = ft.File_Transf_id;

                        ftd.AtualizarRange(ftrange);

                        bool existe = rd.VerificaExisteRegOpt(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), Convert.ToInt32(ViewState["QuoteAtiva"]));

                        ViewState["IdTemporada"] = "";

                        //if (rd.ListarTodosGroup(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text))).Count() > 0)
                        if (existe)
                        {
                            SalvaRangesServicosExistentes("trf", false, Convert.ToInt32(lblSuplID.Text), markupcliente, markupdesconto, lblTituloTransfer.Text, Convert.ToInt32(lblMoedaId.Text), ft.File_Transf_id);
                        }
                        else
                        {
                            SalvaRangesServicosVazio("trf", false, Convert.ToInt32(lblSuplID.Text), markupcliente, markupdesconto, lblTituloTransfer.Text, Convert.ToInt32(lblMoedaId.Text), ft.File_Transf_id);
                        }

                        PopulaNewQuote(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToInt32(ViewState["QuoteAtiva"]));

                    }
                }

                //PopularGridListCarrinhoTransfers(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                //CalculaValorTotal();
                MostrarMsg("Transfer adicionado ao file com sucesso.");

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void btnAddTransferFileNewDirFile(int e)
        {
            try
            {

                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                ClienteDAL cli = new ClienteDAL();
                HolidaysDAL hdal = new HolidaysDAL();
                HolidaysDatesDAL hdatesdal = new HolidaysDatesDAL();
                CidadeDAL cd = new CidadeDAL();

                QuoteTransDAL ftd = new QuoteTransDAL();

                Quotation q = fcd.RetornaQuoteObj(txtQuoteNumber.Text);
                if (q == null)
                {
                    if (txtBaseDeNew.Text.Equals("") || txtBaseAteNew.Text.Equals(""))
                    {
                        MostrarMsg("Selecione uma base inicial para o file.");
                        return;
                    }
                }

                ClienteMarkupDAL climark = new ClienteMarkupDAL();

                DateTime In = Convert.ToDateTime(txtDataFromTrans.Text);
                DateTime Out = Convert.ToDateTime(txtDataToTrans.Text);

                //Cliente_Markup cl = climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue));
                //decimal markupcliente = 0;
                //decimal markupdesconto = 0;
                //if (cl == null)
                //{
                //    MostrarMsg("Esse cliente não possui markup cadastrado.");
                //    return;
                //}
                //else
                //{
                //    markupcliente = Convert.ToDecimal(cl.Markup_hotel);
                //    markupdesconto = Convert.ToDecimal(cl.Markup_descontoHotel);
                //}

                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), In);
                decimal markupcliente = 0, markupdesconto = 0;
                if (mkfile != null)
                {
                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                    markupdesconto = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                }
                else
                {
                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(In);

                    if (mgfile != null)
                    {
                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                        markupdesconto = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                    }
                    else
                    {
                        MostrarMsg("Não existe Markup cadastrado.");
                        return;
                    }
                }

                if (fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])) == null)
                {
                    File_Carrinho fc = new File_Carrinho();

                    fc.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                    fcd.Salvar(fc);
                }

                foreach (DataListItem item in DataListTransfers.Items)
                {

                    if (item.ItemIndex == e)
                    {
                        Label lblTituloTransfer = (Label)item.FindControl("lblTituloTransfer");
                        Label lblSupplierNome = (Label)item.FindControl("lblSupplierNome");
                        Label lblTarifaTotal = (Label)item.FindControl("lblTarifaTotal");
                        Label lblMoeda0 = (Label)item.FindControl("lblMoeda0");
                        Label lblMoedaId = (Label)item.FindControl("lblMoedaId");
                        Label lblSuplID = (Label)item.FindControl("lblSuplID");

                        Quote_Transf ft = new Quote_Transf();
                        MoedaDAL mod = new MoedaDAL();
                        CambioDAL cambDal = new CambioDAL();

                        ServicoDAL servd = new ServicoDAL();
                        S_Servicos ss = servd.ObterPorNome(lblTituloTransfer.Text);

                        if (hdal.VerificaHoliday(Convert.ToDateTime(txtDataFromTrans.Text), ss.Servicos_Id) ||
                            hdal.VerificaHolidayEntreDatas(Convert.ToDateTime(txtDataFromTrans.Text), ss.Servicos_Id) ||
                            hdal.VerificaHolidaySemana(Convert.ToDateTime(txtDataFromTrans.Text), ss.Servicos_Id))
                        {
                            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "AlertarHolidays()", true);
                            return;
                        }

                        if (lblMoedaId.Text != ddlMoeda.SelectedValue)
                        {
                            Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(lblMoedaId.Text), Convert.ToInt32(ddlMoeda.SelectedValue));

                            decimal valor = Convert.ToDecimal(lblTarifaTotal.Text);

                            decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                            ft.Transf_valor = valorComCambio;
                        }
                        else
                        {
                            ft.Transf_valor = Convert.ToDecimal(lblTarifaTotal.Text);
                        }

                        //ft.Trf_CID_id = ObterIdCidadeServico(lblTituloTransfer.Text);

                        if (cd.ObterPorNome(txtAutoCidadeTransfer.Text) != null)
                        {
                            ft.Trf_CID_id = cd.ObterPorNome(txtAutoCidadeTransfer.Text).CID_id;
                        }
                        else
                        {
                            if (servd.ObterPorNomeLista(lblTituloTransfer.Text).Count > 1)
                            {
                                Supplier suppp = new SupplierDAL().ObterSupplierPorNome(lblSupplierNome.Text);
                                if (suppp != null)
                                {
                                    ft.Trf_CID_id = suppp.CID_id;
                                }
                            }
                        }

                        ft.Paxs = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);
                        ft.Paying_Pax = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);
                        ft.Supp_Paying_Pax = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);

                        int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                        ft.Ordem = Ordem;

                        ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                        ft.S_nome = lblSupplierNome.Text;
                        ft.Transf_nome = lblTituloTransfer.Text;
                        ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;
                        ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);


                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        {

                            SupplierDAL sd = new SupplierDAL();
                            MarkupPaisDAL mkd = new MarkupPaisDAL();

                            Supplier spp = sd.ObterPorId(Convert.ToInt32(lblSuplID.Text));
                            MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                            ft.markup = mkp.MarkupServ;
                            ft.desconto = mkp.Desconto;
                            ft.markupNet = markupcliente;
                            ft.descontoNet = markupdesconto;
                        }
                        else
                        {
                            ft.markup = markupcliente;
                            ft.desconto = markupdesconto;
                            ft.markupNet = 0;
                            ft.descontoNet = 0;
                        }

                        ft.Qtd_Transf = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);
                        ft.Data_From = Convert.ToDateTime(txtDataFromTrans.Text);
                        ft.Data_To = Convert.ToDateTime(txtDataToTrans.Text);
                        ft.Trf_Tours = "TRF";
                        ft.Status = "OR";
                        ft.S_id = Convert.ToInt32(lblSuplID.Text);
                        ft.FTC = false;
                        ft.Flag = "servico";
                        ft.Range_id = 0;
                        if (flagTC == 0) ft.TC = false; else ft.TC = true;

                        ftd.Salvar(ft);

                        AcertaRangeDirFile(ft.Quote_Transf_id, "servico");
                        PopularNewFile();
                    }
                }


                if (flagTC == 0)
                {
                    if (fcd.VerificaExisteTCQuotes(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))))
                    {
                        flagTC = 1;
                        btnAddTransferFileNewDirFile(e);
                    }
                }
                else
                {
                    flagTC = 0;
                }

                MostrarMsg("Transfer adicionado ao file com sucesso.");

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void btnAddTransferSubFileNew(int e)
        {
            try
            {

                FileTransfersDAL ftd = new FileTransfersDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                ClienteDAL cli = new ClienteDAL();
                RangeDal rd = new RangeDal();
                SupplierDAL sd = new SupplierDAL();
                CidadeDAL cd = new CidadeDAL();
                ServicoDAL servd = new ServicoDAL();


                File_Carrinho fcarr = fcd.RetornaFileObj(txtQuoteNumber.Text);

                if (fcarr != null)
                {
                    if (rd.ListarTodosGroup(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text))).Count() == 0)
                    {
                        if (txtBaseDeNew.Text.Equals("") || txtBaseAteNew.Text.Equals(""))
                        {
                            MostrarMsg("Selecione uma base inicial para o file.");
                            return;
                        }
                    }
                }

                ClienteMarkupDAL climark = new ClienteMarkupDAL();

                //decimal markupcliente = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_servico);
                //decimal markupdesconto = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_descontoServico);

                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToDateTime(txtDataFromTrans.Text));
                decimal markupcliente = 0, markupdesconto = 0;
                if (mkfile != null)
                {
                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                    markupdesconto = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                }
                else
                {
                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(Convert.ToDateTime(txtDataFromTrans.Text));

                    if (mgfile != null)
                    {
                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                        markupdesconto = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                    }
                    else
                    {
                        MostrarMsg("Não existe Markup cadastrado.");
                        return;
                    }
                }

                if (fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])) == null)
                {
                    File_Carrinho fc = new File_Carrinho();

                    fc.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                    fcd.Salvar(fc);
                }

                foreach (DataListItem item in DataListTransfersSubServicos.Items)
                {

                    if (item.ItemIndex == Convert.ToInt32(e))
                    {

                        Label lblTituloTransfer = (Label)item.FindControl("lblTituloTransfer");
                        Label lblSupplierNome = (Label)item.FindControl("lblSupplierNome");
                        Label lblTarifaTotal = (Label)item.FindControl("lblTarifaTotal");
                        Label lblMoeda0 = (Label)item.FindControl("lblMoeda0");
                        Label lblMoedaId = (Label)item.FindControl("lblMoedaId");
                        Label lblSuplID = (Label)item.FindControl("lblSuplID");
                        Label lblIdMServicoTemporada = (Label)item.FindControl("lblIdMServicoTemporada");

                        File_Transfers ft = new File_Transfers();
                        MoedaDAL mod = new MoedaDAL();
                        CambioDAL cambDal = new CambioDAL();
                        MontaServicoDAL msd = new MontaServicoDAL();

                        ft.Paxs = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);
                        ft.Paying_Pax = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);
                        ft.Supp_Paying_Pax = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);

                        int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                        ft.Ordem = Ordem;

                        //ft.Trf_CID_id = ObterIdCidadeServico(lblTituloTransfer.Text); //Convert.ToInt32(ddlCidadeTransFiltro.SelectedValue);
                        if (cd.ObterPorNome(txtAutoCidadeTransfer.Text) != null)
                        {
                            ft.Trf_CID_id = cd.ObterPorNome(txtAutoCidadeTransfer.Text).CID_id;
                        }
                        else
                        {
                            if (servd.ObterPorNomeLista(lblTituloTransfer.Text).Count > 1)
                            {
                                Supplier suppp = new SupplierDAL().ObterSupplierPorNome(lblSupplierNome.Text);
                                if (suppp != null)
                                {
                                    ft.Trf_CID_id = suppp.CID_id;
                                }
                            }
                        }

                        ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                        ft.S_nome = lblSupplierNome.Text;
                        ft.Transf_nome = lblTituloTransfer.Text;
                        ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;
                        ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);


                        ft.Qtd_Transf = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);
                        ft.Data_From = Convert.ToDateTime(txtDataFromTrans.Text);
                        ft.Data_To = Convert.ToDateTime(txtDataToTrans.Text);
                        ft.Trf_Tours = "TRF";
                        ft.Status = "OR";
                        ft.S_id = Convert.ToInt32(lblSuplID.Text);
                        ft.SubServico = true;
                        ft.FTC = false;

                        ft.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                        ftd.Salvar(ft);

                        File_Transfers ftrange = new File_Transfers();
                        ftrange.Range_id = 0;
                        ftrange.File_Transf_id = ft.File_Transf_id;

                        ftd.AtualizarRange(ftrange);


                        bool existe = rd.VerificaExisteRegOpt(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), Convert.ToInt32(ViewState["QuoteAtiva"]));
                        ViewState["IdTemporada"] = lblIdMServicoTemporada.Text;

                        //if (rd.ListarTodosGroup(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text))).Count() > 0)
                        if (existe)
                        {
                            SalvaRangesServicosExistentes("trf", true, Convert.ToInt32(lblSuplID.Text), markupcliente, markupdesconto, lblTituloTransfer.Text, Convert.ToInt32(lblMoedaId.Text), ft.File_Transf_id);
                        }
                        else
                        {
                            SalvaRangesServicosVazio("trf", true, Convert.ToInt32(lblSuplID.Text), markupcliente, markupdesconto, lblTituloTransfer.Text, Convert.ToInt32(lblMoedaId.Text), ft.File_Transf_id);
                        }

                        PopulaNewQuote(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToInt32(ViewState["QuoteAtiva"]));

                        ServicoCompletoFileDAL scfd = new ServicoCompletoFileDAL();


                        foreach (Servico_Completo scP in msd.ListarTodosSubServicoPorTemporadaLista(Convert.ToInt32(lblIdMServicoTemporada.Text), Convert.ToInt32(ddlNumPaxTransfers.SelectedValue)))
                        {
                            Servico_Completo_File scf = new Servico_Completo_File();

                            scf.IdMServico = scP.IdMServico;
                            scf.File_Transf_id = ft.File_Transf_id;
                            scf.Base_Index = scP.Base_Index;
                            scf.Servicos_Id = scP.Servicos_Id;
                            scf.ServicoCompleto_de = scP.ServicoCompleto_de;
                            scf.ServicoCompleto_ate = scP.ServicoCompleto_ate;

                            int IdBase = scfd.ObterIdBase(Convert.ToInt32(scP.IdMServico), Convert.ToInt32(scP.ServicoCompleto_de), Convert.ToInt32(scP.Base_Index)).Base_id;

                            scf.SupplierID = sd.RetornaPorMServicoValores(Convert.ToInt32(scP.IdMServico), IdBase).S_id;

                            SBasesDAL sbd = new SBasesDAL();
                            int IdMoedaValor = sbd.ObterPorId(IdBase).Moeda_id;

                            if (IdMoedaValor != Convert.ToInt32(ddlMoeda.SelectedValue))
                            {
                                Cambio camb = cambDal.ObterPorIdMoedaPara(IdMoedaValor, Convert.ToInt32(ddlMoeda.SelectedValue));

                                decimal valor = Convert.ToDecimal(scfd.ObterValor(Convert.ToInt32(scP.IdMServico), IdBase).MServico_Valores_Bulk_Total);

                                decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                                scf.Valor = valorComCambio;
                            }
                            else
                            {
                                scf.Valor = scfd.ObterValor(Convert.ToInt32(scP.IdMServico), IdBase).MServico_Valores_Bulk_Total;
                            }

                            scfd.Salvar(scf);

                        }



                    }
                }

                //PopularGridListCarrinhoTransfers(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                //CalculaValorTotal();
                MostrarMsg("Transfer adicionado ao file com sucesso.");

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void btnAddTransferSubFileNewDirFile(int e)
        {
            try
            {

                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                ClienteDAL cli = new ClienteDAL();
                HolidaysDAL hdal = new HolidaysDAL();
                HolidaysDatesDAL hdatesdal = new HolidaysDatesDAL();
                CidadeDAL cdal = new CidadeDAL();

                QuoteTransDAL ftd = new QuoteTransDAL();

                Quotation q = fcd.RetornaQuoteObj(txtQuoteNumber.Text);
                if (q == null)
                {
                    if (txtBaseDeNew.Text.Equals("") || txtBaseAteNew.Text.Equals(""))
                    {
                        MostrarMsg("Selecione uma base inicial para o file.");
                        return;
                    }
                }

                ClienteMarkupDAL climark = new ClienteMarkupDAL();

                DateTime In = Convert.ToDateTime(txtDataFromTrans.Text);
                DateTime Out = Convert.ToDateTime(txtDataToTrans.Text);

                //Cliente_Markup cl = climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue));
                //decimal markupcliente = 0;
                //decimal markupdesconto = 0;
                //if (cl == null)
                //{
                //    MostrarMsg("Esse cliente não possui markup cadastrado.");
                //    return;
                //}
                //else
                //{
                //    markupcliente = Convert.ToDecimal(cl.Markup_hotel);
                //    markupdesconto = Convert.ToDecimal(cl.Markup_descontoHotel);
                //}

                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), In);
                decimal markupcliente = 0, markupdesconto = 0;
                if (mkfile != null)
                {
                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                    markupdesconto = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                }
                else
                {
                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(In);

                    if (mgfile != null)
                    {
                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                        markupdesconto = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                    }
                    else
                    {
                        MostrarMsg("Não existe Markup cadastrado.");
                        return;
                    }
                }

                if (fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])) == null)
                {
                    File_Carrinho fc = new File_Carrinho();

                    fc.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                    fcd.Salvar(fc);
                }

                foreach (DataListItem item in DataListTransfersSubServicos.Items)
                {

                    if (item.ItemIndex == e)
                    {

                        Label lblTituloTransfer = (Label)item.FindControl("lblTituloTransfer");
                        Label lblSupplierNome = (Label)item.FindControl("lblSupplierNome");
                        Label lblTarifaTotal = (Label)item.FindControl("lblTarifaTotal");
                        Label lblMoeda0 = (Label)item.FindControl("lblMoeda0");
                        Label lblMoedaId = (Label)item.FindControl("lblMoedaId");
                        Label lblSuplID = (Label)item.FindControl("lblSuplID");
                        Label lblIdMServicoTemporada = (Label)item.FindControl("lblIdMServicoTemporada");

                        Quote_Transf ft = new Quote_Transf();
                        MoedaDAL mod = new MoedaDAL();
                        CambioDAL cambDal = new CambioDAL();

                        MontaServicoDAL msd = new MontaServicoDAL();

                        ServicoDAL servd = new ServicoDAL();
                        S_Servicos ss = servd.ObterPorNome(lblTituloTransfer.Text);

                        if (hdal.VerificaHoliday(Convert.ToDateTime(txtDataFromTrans.Text), ss.Servicos_Id) ||
                             hdal.VerificaHolidayEntreDatas(Convert.ToDateTime(txtDataFromTrans.Text), ss.Servicos_Id) ||
                             hdal.VerificaHolidaySemana(Convert.ToDateTime(txtDataFromTrans.Text), ss.Servicos_Id))
                        {
                            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "AlertarHolidays()", true);
                            return;
                        }

                        if (lblMoedaId.Text != ddlMoeda.SelectedValue)
                        {
                            Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(lblMoedaId.Text), Convert.ToInt32(ddlMoeda.SelectedValue));

                            decimal valor = Convert.ToDecimal(lblTarifaTotal.Text);

                            decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                            ft.Transf_valor = valorComCambio;
                        }
                        else
                        {
                            ft.Transf_valor = Convert.ToDecimal(lblTarifaTotal.Text);
                        }

                        ft.Paxs = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);
                        ft.Paying_Pax = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);
                        ft.Supp_Paying_Pax = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);

                        int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                        ft.Ordem = Ordem;

                        //ft.Trf_CID_id = ObterIdCidadeServico(lblTituloTransfer.Text);
                        if (cdal.ObterPorNome(txtAutoCidadeTransfer.Text) != null)
                        {
                            ft.Trf_CID_id = cdal.ObterPorNome(txtAutoCidadeTransfer.Text).CID_id;
                        }
                        else
                        {
                            if (servd.ObterPorNomeLista(lblTituloTransfer.Text).Count > 1)
                            {
                                Supplier suppp = new SupplierDAL().ObterSupplierPorNome(lblSupplierNome.Text);
                                if (suppp != null)
                                {
                                    ft.Trf_CID_id = suppp.CID_id;
                                }
                            }
                        }

                        ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                        ft.S_nome = lblSupplierNome.Text;
                        ft.Transf_nome = lblTituloTransfer.Text;
                        ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;
                        ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);

                        SupplierDAL sd = new SupplierDAL();

                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        {
                            MarkupPaisDAL mkd = new MarkupPaisDAL();

                            Supplier spp = sd.ObterPorId(Convert.ToInt32(lblSuplID.Text));
                            MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                            ft.markup = mkp.MarkupServ;
                            ft.desconto = mkp.Desconto;
                            ft.markupNet = markupcliente;
                            ft.descontoNet = markupdesconto;
                        }
                        else
                        {
                            ft.markup = markupcliente;
                            ft.desconto = markupdesconto;
                            ft.markupNet = 0;
                            ft.descontoNet = 0;
                        }


                        ft.Qtd_Transf = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);
                        ft.Data_From = Convert.ToDateTime(txtDataFromTrans.Text);
                        ft.Data_To = Convert.ToDateTime(txtDataToTrans.Text);
                        ft.Trf_Tours = "TRF";
                        ft.Status = "OR";
                        ft.S_id = Convert.ToInt32(lblSuplID.Text);
                        ft.SubServico = true;
                        ft.FTC = false;
                        ft.Flag = "servico";
                        ft.Range_id = 0;
                        if (flagTC == 0) ft.TC = false; else ft.TC = true;

                        ftd.Salvar(ft);


                        SubServicosFileDAL ssfdal = new SubServicosFileDAL();
                        MontaServicoDAL mserdal = new MontaServicoDAL();

                        Array tes = mserdal.ListarTodosSubServicoPorTemporadaArray(Convert.ToInt32(lblIdMServicoTemporada.Text), Convert.ToInt32(ft.Paying_Pax));

                        foreach (var arr in tes)
                        {
                            string[] separators = { ", ", "=", "{", "}" };
                            string value = arr.ToString();
                            string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);

                            SubServicosFile ssf = new SubServicosFile();
                            ssf.NomeSupplier = words[1].Trim();
                            ssf.ServDe = ft.Paying_Pax.ToString();
                            ssf.ServAte = ft.Paying_Pax.ToString();
                            ssf.NomeFantasia = words[9].Trim();
                            ssf.NomeSubItem = words[11].Trim();
                            //ssf.Moeda_id = Convert.ToInt32(words[13]);
                            //ssf.Moeda = words[15].Trim();

                            decimal val = 0;
                            if (Convert.ToInt32(words[17]) == 1)
                                val = Convert.ToDecimal(words[7]) / Convert.ToDecimal(ft.Paying_Pax.ToString());
                            else
                                val = Convert.ToDecimal(words[7]);

                            if (Convert.ToInt32(words[13]).ToString() != ddlMoeda.SelectedValue)
                            {
                                Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(words[13]), Convert.ToInt32(ddlMoeda.SelectedValue));
                                decimal valorComCambio = val * Convert.ToDecimal(camb.Cambio1);
                                ssf.Valor = valorComCambio;
                            }
                            else ssf.Valor = val;

                            ssf.Quote_Transf_id = ft.Quote_Transf_id;

                            ssfdal.Salvar(ssf);
                        }


                        AcertaRangeDirFile(ft.Quote_Transf_id, "servico");

                        PopularNewFile();

                        ServicoCompletoFileDAL scfd = new ServicoCompletoFileDAL();

                        foreach (Servico_Completo scP in msd.ListarTodosSubServicoPorTemporadaLista(Convert.ToInt32(lblIdMServicoTemporada.Text), Convert.ToInt32(ddlNumPaxTransfers.SelectedValue)))
                        {
                            Servico_Completo_File scf = new Servico_Completo_File();

                            scf.IdMServico = scP.IdMServico;
                            scf.Quote_Transf_id = ft.Quote_Transf_id;
                            scf.Base_Index = scP.Base_Index;
                            scf.Servicos_Id = scP.Servicos_Id;
                            scf.ServicoCompleto_de = scP.ServicoCompleto_de;
                            scf.ServicoCompleto_ate = scP.ServicoCompleto_ate;

                            int IdBase = scfd.ObterIdBase(Convert.ToInt32(scP.IdMServico), Convert.ToInt32(scP.ServicoCompleto_de), Convert.ToInt32(scP.Base_Index)).Base_id;

                            scf.SupplierID = sd.RetornaPorMServicoValores(Convert.ToInt32(scP.IdMServico), IdBase).S_id;

                            SBasesDAL sbd = new SBasesDAL();
                            int IdMoedaValor = sbd.ObterPorId(IdBase).Moeda_id;

                            if (IdMoedaValor != Convert.ToInt32(ddlMoeda.SelectedValue))
                            {
                                Cambio camb = cambDal.ObterPorIdMoedaPara(IdMoedaValor, Convert.ToInt32(ddlMoeda.SelectedValue));

                                decimal valor = Convert.ToDecimal(scfd.ObterValor(Convert.ToInt32(scP.IdMServico), IdBase).MServico_Valores_Bulk_Total);

                                decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                                scf.Valor = valorComCambio;
                            }
                            else
                            {
                                scf.Valor = scfd.ObterValor(Convert.ToInt32(scP.IdMServico), IdBase).MServico_Valores_Bulk_Total;
                            }

                            scfd.Salvar(scf);

                        }
                    }
                }


                if (flagTC == 0)
                {
                    if (fcd.VerificaExisteTCQuotes(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))))
                    {
                        flagTC = 1;
                        btnAddTransferSubFileNewDirFile(e);
                    }
                }
                else
                {
                    flagTC = 0;
                }

                MostrarMsg("Transfer adicionado ao file com sucesso.");

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected decimal RetornaValoresBaseNova(bool SubServico, int IdCidade, DateTime dtFrom, DateTime dtTo, int IdSupplier, int numRange, string trfNome, decimal markup, decimal desconto, decimal markupNet, decimal descontoNet, int paypax)
        {
            SBaseValorDAL sbaseV = new SBaseValorDAL();
            MontaServicoDAL msd = new MontaServicoDAL();

            try
            {
                Monta_Servico_Valores msvv = new Monta_Servico_Valores();

                if (SubServico)
                {
                    S_Bases_Valor sbv = sbaseV.ObterValorSub(Convert.ToInt32(IdSupplier),
                                                             trfNome,
                                                             Convert.ToDateTime(dtFrom),
                                                             Convert.ToDateTime(dtTo),
                                                             Convert.ToInt32(numRange));

                    if (sbv == null)
                    {
                        return 0;
                    }

                    return Convert.ToDecimal(sbv.S_Bases_Valor_valor);
                }
                else
                {
                    if (IdCidade != 0)
                    {

                        msvv = msd.ObterValorTransfers(Convert.ToDateTime(dtFrom),
                                                                            Convert.ToDateTime(dtTo),
                                                                            Convert.ToInt32(IdSupplier),
                                                                            Convert.ToInt32(numRange),
                                                                            trfNome,
                                                                            Convert.ToInt32(IdCidade));
                    }
                    else
                    {
                        msvv = msd.ObterValorTransfers(Convert.ToDateTime(dtFrom),
                                                                             Convert.ToDateTime(dtTo),
                                                                             Convert.ToInt32(IdSupplier),
                                                                             Convert.ToInt32(numRange),
                                                                             trfNome);
                    }

                    if (msvv == null)
                    {
                        return 0;
                    }

                    return Convert.ToDecimal(msvv.MServico_Valores_Bulk_Total);
                }

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }

            return 0;
        }

        protected void SalvaRangesServicosExistentes(string TipoServ, bool SubServico, int IdSupplier, decimal markupcliente, decimal markupdesconto, string nomeTransfer, int IdMoeda, int IdTransfer)
        {
            try
            {
                RangeDal rd = new RangeDal();
                FileTransfersDAL ftd = new FileTransfersDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                CambioDAL cambDal = new CambioDAL();
                MontaServicoDAL mserdal = new MontaServicoDAL();

                int IdQuot = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));

                int num = 0;
                bool exists2;
                List<string> BasesAdicionadas2 = new List<string>();
                List<int> RangesID = new List<int>();
                List<int> ids = new List<int>();


                foreach (Ranges rgs in rd.ListarTodos(IdQuot, Convert.ToInt32(ViewState["QuoteAtiva"])))
                {

                    if (!rgs.Ranges_de.Equals("TC"))
                    {
                        exists2 = BasesAdicionadas2.Exists(element => element.Equals(rgs.Ranges_de));
                        num = 1;
                    }
                    else
                    {
                        exists2 = false;
                    }

                    if (!exists2 && num == 1)
                    {
                        BasesAdicionadas2.Add(rgs.Ranges_de);

                        if (rgs.Ranges_de.Equals("TC"))
                        {
                            num = 0;
                        }

                        int[] arrayOf = ids.ToArray();

                        Ranges range = new Ranges();
                        range.Ranges_de = rgs.Ranges_de;
                        range.Ranges_ate = rgs.Ranges_ate;
                        range.Quotation_Id = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));
                        range.Flag = "servico";

                        range.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                        if (rd.ObterPorTarifaOne(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), rgs.Ranges_de, rgs.Ranges_ate) != null)
                        {
                            range.Ordem = rd.ObterPorTarifaOne(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), rgs.Ranges_de, rgs.Ranges_ate).Ordem;
                        }
                        else
                        {
                            range.Ordem = rd.ObterPorTarifaLast(IdTransfer).Ordem + 1;
                        }


                        if (rgs.Ranges_de.Equals("TC", StringComparison.OrdinalIgnoreCase))
                        {
                            range.RangeID = arrayOf[0];
                            range.QtdTC = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);

                            int numToRemove = arrayOf[0];
                            arrayOf = arrayOf.Where(val => val != numToRemove).ToArray();
                            ids.Clear();
                        }


                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        {

                            SupplierDAL sd = new SupplierDAL();
                            MarkupPaisDAL mkd = new MarkupPaisDAL();

                            Supplier spp = sd.ObterPorId(Convert.ToInt32(IdSupplier));
                            MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                            range.markup = mkp.Markup;
                            range.desconto = mkp.Desconto;
                            range.markupNet = markupcliente;
                            range.descontoNet = markupdesconto;
                        }
                        else
                        {
                            range.markup = markupcliente;
                            range.desconto = markupdesconto;
                            range.markupNet = 0;
                            range.descontoNet = 0;
                        }

                        decimal valor = 0;

                        if (rgs.Ranges_de.Equals("TC", StringComparison.OrdinalIgnoreCase))
                        {
                            range.Valor = 0;
                        }
                        else
                        {
                            if (TipoServ.Equals("trf"))
                            {
                                valor = RetornaValoresBaseNova(SubServico, Convert.ToInt32(ViewState["IdCidadeTransfer"]), Convert.ToDateTime(txtDataFromTrans.Text), Convert.ToDateTime(txtDataToTrans.Text),
                                       Convert.ToInt32(IdSupplier), Convert.ToInt32(rgs.Ranges_de), nomeTransfer, Convert.ToDecimal(range.markup),
                                       Convert.ToDecimal(range.desconto), Convert.ToDecimal(range.markupNet), Convert.ToDecimal(range.descontoNet), Convert.ToInt32(ddlNumPaxTransfers.SelectedValue));
                            }
                            else
                            {
                                valor = RetornaValoresBaseNova(SubServico, Convert.ToInt32(ViewState["IdCidadeTransfer"]), Convert.ToDateTime(txtDataFromTours.Text), Convert.ToDateTime(txtDataToTours.Text),
                                       Convert.ToInt32(IdSupplier), Convert.ToInt32(rgs.Ranges_de), nomeTransfer, Convert.ToDecimal(range.markup),
                                       Convert.ToDecimal(range.desconto), Convert.ToDecimal(range.markupNet), Convert.ToDecimal(range.descontoNet), Convert.ToInt32(ddlNumPaxTransfers.SelectedValue));
                            }

                            if (IdMoeda.ToString() != ddlMoeda.SelectedValue)
                            {
                                Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(IdMoeda), Convert.ToInt32(ddlMoeda.SelectedValue));

                                decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                                range.Valor = valorComCambio;
                            }
                            else
                            {
                                range.Valor = valor;
                            }
                        }


                        range.FileTabelaId = IdTransfer;

                        rd.Salvar(range);

                        if (!ViewState["IdTemporada"].Equals(""))
                        {
                            SubServicosFileDAL ssfdal = new SubServicosFileDAL();

                            Ranges rTC = rd.ObterPorId(Convert.ToInt32(range.RangeID));

                            Array tes;

                            if (!range.Ranges_de.Equals("TC", StringComparison.OrdinalIgnoreCase))
                            {
                                tes = mserdal.ListarTodosSubServicoPorTemporadaArray(Convert.ToInt32(ViewState["IdTemporada"]), Convert.ToInt32(rgs.Ranges_de));
                            }
                            else
                            {
                                tes = mserdal.ListarTodosSubServicoPorTemporadaArray(Convert.ToInt32(ViewState["IdTemporada"]), Convert.ToInt32(rTC.Ranges_de));
                            }

                            foreach (var item in tes)
                            {
                                string[] separators = { ", ", "=", "{", "}" };
                                string value = item.ToString();
                                string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);

                                SubServicosFile ssf = new SubServicosFile();
                                ssf.NomeSupplier = words[1].Trim();
                                ssf.ServDe = range.Ranges_de;
                                ssf.ServAte = range.Ranges_ate;
                                ssf.NomeFantasia = words[9].Trim();
                                ssf.NomeSubItem = words[11].Trim();
                                //ssf.Moeda_id = Convert.ToInt32(words[13]);
                                //ssf.Moeda = words[15].Trim();

                                decimal val = 0;
                                if (!range.Ranges_de.Equals("TC", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (Convert.ToInt32(words[17]) == 1)
                                        val = Convert.ToDecimal(words[7]) / Convert.ToDecimal(range.Ranges_de);
                                    else
                                        val = Convert.ToDecimal(words[7]);
                                }
                                else
                                {
                                    if (Convert.ToInt32(words[17]) == 1)
                                        val = Convert.ToDecimal(words[7]) / Convert.ToDecimal(rTC.Ranges_de);
                                    else
                                        val = Convert.ToDecimal(words[7]);
                                }

                                if (Convert.ToInt32(words[13]).ToString() != ddlMoeda.SelectedValue)
                                {
                                    Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(words[13]), Convert.ToInt32(ddlMoeda.SelectedValue));
                                    decimal valorComCambio = val * Convert.ToDecimal(camb.Cambio1);
                                    ssf.Valor = valorComCambio;
                                }
                                else ssf.Valor = val;

                                ssf.Ranges_id = range.Ranges_id;

                                ssfdal.Salvar(ssf);
                            }
                        }

                        if (!range.Ranges_de.Equals("TC", StringComparison.OrdinalIgnoreCase))
                        {
                            ids.Add(range.Ranges_id);
                        }

                        if (range.Ranges_de.Equals("TC", StringComparison.OrdinalIgnoreCase))
                        {
                            AcertaRange(Convert.ToInt32(range.RangeID), IdTransfer, range.Flag);
                        }
                        else
                        {
                            AcertaRange(range.Ranges_id, IdTransfer, range.Flag);
                        }

                    }



                }


            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void SalvaRangesServicosVazio(string TipoServ, bool SubServico, int IdSupplier, decimal markupcliente, decimal markupdesconto, string nomeTransfer, int IdMoeda, int IdTransfer)
        {
            try
            {
                RangeDal rd = new RangeDal();
                FileTransfersDAL ftd = new FileTransfersDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                CambioDAL cambDal = new CambioDAL();
                MontaServicoDAL mservdal = new MontaServicoDAL();

                Ranges range = new Ranges();
                range.Ranges_de = txtBaseDeNew.Text;
                range.Ranges_ate = txtBaseAteNew.Text;
                range.Quotation_Id = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));
                range.Flag = "servico";

                range.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                bool existe = rd.VerificaExisteRegOpt(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), Convert.ToInt32(ViewState["QuoteAtiva"]));

                //if (rd.ListarTodosGroup(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text))).Count == 0)
                if (!existe)
                {
                    range.Ordem = 1;
                }
                else
                {
                    range.Ordem = rd.ObterPorTarifaLast(IdTransfer, "servico").Ordem + 1;
                }

                if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                {
                    SupplierDAL sd = new SupplierDAL();
                    MarkupPaisDAL mkd = new MarkupPaisDAL();

                    Supplier spp = sd.ObterPorId(Convert.ToInt32(IdSupplier));
                    MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                    range.markup = mkp.Markup;
                    range.desconto = mkp.Desconto;
                    range.markupNet = markupcliente;
                    range.descontoNet = markupdesconto;
                }
                else
                {
                    range.markup = markupcliente;
                    range.desconto = markupdesconto;
                    range.markupNet = 0;
                    range.descontoNet = 0;
                }

                decimal valor = 0;

                if (txtBaseDeNew.Text.Equals("tc", StringComparison.OrdinalIgnoreCase))
                {
                    range.Valor = 0;
                }
                else
                {
                    if (TipoServ.Equals("add"))
                    {
                        valor = RetornaValoresBaseNova(SubServico, Convert.ToInt32(ViewState["IdCidadeTransfer"]), Convert.ToDateTime(ViewState["DatasAddBaseFrom"]), Convert.ToDateTime(ViewState["DatasAddBaseTo"]),
                               Convert.ToInt32(IdSupplier), Convert.ToInt32(txtBaseDeNew.Text), nomeTransfer, Convert.ToDecimal(range.markup),
                               Convert.ToDecimal(range.desconto), Convert.ToDecimal(range.markupNet), Convert.ToDecimal(range.descontoNet), Convert.ToInt32(ddlNumPaxTransfers.SelectedValue));
                    }
                    else if (TipoServ.Equals("trf"))
                    {
                        valor = RetornaValoresBaseNova(SubServico, Convert.ToInt32(ViewState["IdCidadeTransfer"]), Convert.ToDateTime(txtDataFromTrans.Text), Convert.ToDateTime(txtDataToTrans.Text),
                               Convert.ToInt32(IdSupplier), Convert.ToInt32(txtBaseDeNew.Text), nomeTransfer, Convert.ToDecimal(range.markup),
                               Convert.ToDecimal(range.desconto), Convert.ToDecimal(range.markupNet), Convert.ToDecimal(range.descontoNet), Convert.ToInt32(ddlNumPaxTransfers.SelectedValue));
                    }
                    else
                    {
                        valor = RetornaValoresBaseNova(SubServico, Convert.ToInt32(ViewState["IdCidadeTransfer"]), Convert.ToDateTime(txtDataFromTours.Text), Convert.ToDateTime(txtDataToTours.Text),
                               Convert.ToInt32(IdSupplier), Convert.ToInt32(txtBaseDeNew.Text), nomeTransfer, Convert.ToDecimal(range.markup),
                               Convert.ToDecimal(range.desconto), Convert.ToDecimal(range.markupNet), Convert.ToDecimal(range.descontoNet), Convert.ToInt32(ddlNumPaxTransfers.SelectedValue));
                    }


                    if (IdMoeda.ToString() != ddlMoeda.SelectedValue)
                    {
                        Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(IdMoeda), Convert.ToInt32(ddlMoeda.SelectedValue));

                        decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                        range.Valor = valorComCambio;
                    }
                    else
                    {
                        range.Valor = valor;
                    }

                }

                range.FileTabelaId = IdTransfer;

                rd.Salvar(range);

                SubServicosFileDAL ssfdal = new SubServicosFileDAL();

                List<SubServicosFile> listSubSF = ViewState["sublista"] as List<SubServicosFile>;

                if (listSubSF.Count > 0)
                {
                    foreach (var item in listSubSF)
                    {
                        SubServicosFile ssf = new SubServicosFile();
                        ssf.NomeSupplier = item.NomeSupplier;
                        ssf.ServDe = txtBaseDeNew.Text;
                        ssf.ServAte = txtBaseAteNew.Text;
                        ssf.NomeFantasia = item.NomeFantasia;
                        ssf.NomeSubItem = item.NomeSubItem;
                        ssf.Valor = item.Valor;
                        ssf.Ranges_id = range.Ranges_id;
                        ssfdal.Salvar(ssf);
                    }
                }

                if (listSubSF.Count == 0)
                {
                    if (ViewState["IdTemporada"] != "")
                    {

                        //Array tes = mservdal.ListarTodosSubServicoPorTemporadaArray(Convert.ToInt32(ViewState["IdTemporada"]), Convert.ToInt32(range.Ranges_de));

                        Ranges rTC = rd.ObterPorId(Convert.ToInt32(range.RangeID));

                        Array tes;

                        if (!range.Ranges_de.Equals("TC", StringComparison.OrdinalIgnoreCase))
                        {
                            tes = mservdal.ListarTodosSubServicoPorTemporadaArray(Convert.ToInt32(ViewState["IdTemporada"]), Convert.ToInt32(range.Ranges_de));
                        }
                        else
                        {
                            tes = mservdal.ListarTodosSubServicoPorTemporadaArray(Convert.ToInt32(ViewState["IdTemporada"]), Convert.ToInt32(rTC.Ranges_de));
                        }

                        foreach (var item in tes)
                        {
                            string[] separators = { ", ", "=", "{", "}" };
                            string value = item.ToString();
                            string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);

                            SubServicosFile ssf = new SubServicosFile();
                            ssf.NomeSupplier = words[1].Trim();
                            ssf.ServDe = range.Ranges_de;
                            ssf.ServAte = range.Ranges_ate;
                            ssf.NomeFantasia = words[9].Trim();
                            ssf.NomeSubItem = words[11].Trim();
                            //ssf.Moeda_id = Convert.ToInt32(words[13]);
                            //ssf.Moeda = words[15].Trim();

                            decimal val = 0;
                            if (!range.Ranges_de.Equals("TC", StringComparison.OrdinalIgnoreCase))
                            {
                                if (Convert.ToInt32(words[17]) == 1)
                                    val = Convert.ToDecimal(words[7]) / Convert.ToDecimal(range.Ranges_de);
                                else
                                    val = Convert.ToDecimal(words[7]);
                            }
                            else
                            {
                                if (Convert.ToInt32(words[17]) == 1)
                                    val = Convert.ToDecimal(words[7]) / Convert.ToDecimal(rTC.Ranges_de);
                                else
                                    val = Convert.ToDecimal(words[7]);
                            }

                            if (Convert.ToInt32(words[13]).ToString() != ddlMoeda.SelectedValue)
                            {
                                Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(words[13]), Convert.ToInt32(ddlMoeda.SelectedValue));
                                decimal valorComCambio = val * Convert.ToDecimal(camb.Cambio1);
                                ssf.Valor = valorComCambio;
                            }
                            else ssf.Valor = val;

                            ssf.Ranges_id = range.Ranges_id;

                            ssfdal.Salvar(ssf);
                        }
                    }
                }

                AcertaRange(range.Ranges_id, IdTransfer, range.Flag);

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void BtnAddTransferFileSub(object sender, CommandEventArgs e)
        {
            if (rdoOptFileTranfers.SelectedValue.Equals("0"))
            {
                btnAddTransferSubFileNew(Convert.ToInt32(e.CommandArgument));
            }
            else
            {
                btnAddTransferSubFileNewDirFile(Convert.ToInt32(e.CommandArgument));
            }
            //btnAddTransferFileSub_Click(sender, e);
        }

        protected void btnAddTransferFileSub_Click(object sender, CommandEventArgs e)
        {
            try
            {

                FileTransfersDAL ftd = new FileTransfersDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                ClienteDAL cli = new ClienteDAL();

                ClienteMarkupDAL climark = new ClienteMarkupDAL();

                HolidaysDAL hdal = new HolidaysDAL();
                HolidaysDatesDAL hdatesdal = new HolidaysDatesDAL();


                //decimal markupcliente = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_servico);
                //decimal markupdesconto = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_descontoServico);

                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToDateTime(txtDataFromTrans.Text));
                decimal markupcliente = 0, markupdesconto = 0;
                if (mkfile != null)
                {
                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                    markupdesconto = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                }
                else
                {
                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(Convert.ToDateTime(txtDataFromTrans.Text));

                    if (mgfile != null)
                    {
                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                        markupdesconto = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                    }
                    else
                    {
                        MostrarMsg("Não existe Markup cadastrado.");
                        return;
                    }
                }

                if (fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])) == null)
                {
                    File_Carrinho fc = new File_Carrinho();

                    fc.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                    fcd.Salvar(fc);
                }

                foreach (DataListItem item in DataListTransfersSubServicos.Items)
                {

                    if (item.ItemIndex == Convert.ToInt32(e.CommandArgument))
                    {

                        //btnAddTransferSubFileNew(Convert.ToInt32(e.CommandArgument));

                        Label lblTituloTransfer = (Label)item.FindControl("lblTituloTransfer");
                        Label lblSupplierNome = (Label)item.FindControl("lblSupplierNome");
                        Label lblTarifaTotal = (Label)item.FindControl("lblTarifaTotal");
                        Label lblMoeda0 = (Label)item.FindControl("lblMoeda0");
                        Label lblMoedaId = (Label)item.FindControl("lblMoedaId");
                        Label lblSuplID = (Label)item.FindControl("lblSuplID");
                        Label lblIdMServicoTemporada = (Label)item.FindControl("lblIdMServicoTemporada");

                        File_Transfers ft = new File_Transfers();
                        MoedaDAL mod = new MoedaDAL();
                        CambioDAL cambDal = new CambioDAL();

                        MontaServicoDAL msd = new MontaServicoDAL();

                        ServicoDAL servd = new ServicoDAL();
                        S_Servicos ss = servd.ObterPorNome(lblTituloTransfer.Text);

                        if (hdal.VerificaHoliday(Convert.ToDateTime(txtDataFromTrans.Text), ss.Servicos_Id) ||
                             hdal.VerificaHolidayEntreDatas(Convert.ToDateTime(txtDataFromTrans.Text), ss.Servicos_Id) ||
                             hdal.VerificaHolidaySemana(Convert.ToDateTime(txtDataFromTrans.Text), ss.Servicos_Id))
                        {
                            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "AlertarHolidays()", true);
                            return;
                        }

                        if (lblMoedaId.Text != ddlMoeda.SelectedValue)
                        {
                            Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(lblMoedaId.Text), Convert.ToInt32(ddlMoeda.SelectedValue));

                            decimal valor = Convert.ToDecimal(lblTarifaTotal.Text);

                            decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                            ft.Transf_valor = valorComCambio;
                        }
                        else
                        {
                            ft.Transf_valor = Convert.ToDecimal(lblTarifaTotal.Text);
                        }

                        ft.Paxs = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);
                        ft.Paying_Pax = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);
                        ft.Supp_Paying_Pax = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);

                        int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                        ft.Ordem = Ordem;

                        ft.Trf_CID_id = ObterIdCidadeServico(lblTituloTransfer.Text); //Convert.ToInt32(ddlCidadeTransFiltro.SelectedValue);

                        ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                        ft.S_nome = lblSupplierNome.Text;
                        ft.Transf_nome = lblTituloTransfer.Text;
                        ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;
                        ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);

                        SupplierDAL sd = new SupplierDAL();

                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        {
                            MarkupPaisDAL mkd = new MarkupPaisDAL();

                            Supplier spp = sd.ObterPorId(Convert.ToInt32(lblSuplID.Text));
                            MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                            ft.markup = mkp.MarkupServ;
                            ft.desconto = mkp.Desconto;
                            ft.markupNet = markupcliente;
                            ft.descontoNet = markupdesconto;
                        }
                        else
                        {
                            ft.markup = markupcliente;
                            ft.desconto = markupdesconto;
                            ft.markupNet = 0;
                            ft.descontoNet = 0;
                        }


                        ft.Qtd_Transf = Convert.ToInt32(ddlNumPaxTransfers.SelectedValue);
                        ft.Data_From = Convert.ToDateTime(txtDataFromTrans.Text);
                        ft.Data_To = Convert.ToDateTime(txtDataToTrans.Text);
                        ft.Trf_Tours = "TRF";
                        ft.Status = "OR";
                        ft.S_id = Convert.ToInt32(lblSuplID.Text);
                        ft.SubServico = true;
                        ft.FTC = false;

                        ftd.Salvar(ft);

                        ServicoCompletoFileDAL scfd = new ServicoCompletoFileDAL();

                        foreach (Servico_Completo scP in msd.ListarTodosSubServicoPorTemporadaLista(Convert.ToInt32(lblIdMServicoTemporada.Text), Convert.ToInt32(ddlNumPaxTransfers.SelectedValue)))
                        {
                            Servico_Completo_File scf = new Servico_Completo_File();

                            scf.IdMServico = scP.IdMServico;
                            scf.File_Transf_id = ft.File_Transf_id;
                            scf.Base_Index = scP.Base_Index;
                            scf.Servicos_Id = scP.Servicos_Id;
                            scf.ServicoCompleto_de = scP.ServicoCompleto_de;
                            scf.ServicoCompleto_ate = scP.ServicoCompleto_ate;

                            int IdBase = scfd.ObterIdBase(Convert.ToInt32(scP.IdMServico), Convert.ToInt32(scP.ServicoCompleto_de), Convert.ToInt32(scP.Base_Index)).Base_id;

                            scf.SupplierID = sd.RetornaPorMServicoValores(Convert.ToInt32(scP.IdMServico), IdBase).S_id;

                            SBasesDAL sbd = new SBasesDAL();
                            int IdMoedaValor = sbd.ObterPorId(IdBase).Moeda_id;

                            if (IdMoedaValor != Convert.ToInt32(ddlMoeda.SelectedValue))
                            {
                                Cambio camb = cambDal.ObterPorIdMoedaPara(IdMoedaValor, Convert.ToInt32(ddlMoeda.SelectedValue));

                                decimal valor = Convert.ToDecimal(scfd.ObterValor(Convert.ToInt32(scP.IdMServico), IdBase).MServico_Valores_Bulk_Total);

                                decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                                scf.Valor = valorComCambio;
                            }
                            else
                            {
                                scf.Valor = scfd.ObterValor(Convert.ToInt32(scP.IdMServico), IdBase).MServico_Valores_Bulk_Total;
                            }

                            scfd.Salvar(scf);
                        }
                    }
                }

                PopularGridListCarrinhoTransfers(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                CalculaValorTotal();
                MostrarMsg("Transfer adicionado ao file com sucesso.");

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void imgAtualizaCarrinhoTransfers_Command(object sender, CommandEventArgs e)
        {
            try
            {
                //PopularGridListCarrinhoTransfers(Convert.ToInt32(ViewState["IdQuotGrupo"]));

                FileTransfersDAL ftd = new FileTransfersDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                int IdTarifa = Convert.ToInt32(e.CommandArgument);

                foreach (GridViewRow item in GridFileCarrinhoTransfers.Rows)
                {
                    TextBox txtQtdTarifas = (TextBox)item.FindControl("txtQtdTarifas");
                    Label IdFileTarifa = (Label)item.FindControl("IdFileTarifa");
                    TextBox txtMarkup = (TextBox)item.FindControl("txtMarkup");
                    TextBox txtMarkupNet = (TextBox)item.FindControl("txtMarkupNet");
                    TextBox txtDescontoNet = (TextBox)item.FindControl("txtDescontoNet");
                    TextBox txtDesconto = (TextBox)item.FindControl("txtDesconto");
                    TextBox txtValorTarifas = (TextBox)item.FindControl("txtValorTarifas");

                    if (IdTarifa == Convert.ToInt32(IdFileTarifa.Text))
                    {
                        File_Transfers ft = new File_Transfers();

                        ft.Transf_valor = Convert.ToDecimal(txtValorTarifas.Text);
                        ft.markup = Convert.ToDecimal(txtMarkup.Text);
                        ft.markupNet = Convert.ToDecimal(txtMarkupNet.Text);
                        ft.desconto = Convert.ToDecimal(txtDesconto.Text);
                        ft.descontoNet = Convert.ToDecimal(txtDescontoNet.Text);
                        ft.Qtd_Transf = Convert.ToInt32(txtQtdTarifas.Text);
                        ft.File_Transf_id = IdTarifa;
                        ft.UpdVenda = false;

                        ftd.Atualizar(ft);
                    }

                }


                PopularGridListCarrinhoTransfers(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                CalculaValorTotal();
                MostrarMsg("File atualizado com sucesso.");

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void imgAtualizaCarrinhoTransfersVenda_Command(object sender, CommandEventArgs e)
        {
            try
            {
                FileTransfersDAL ftd = new FileTransfersDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                int IdTarifa = Convert.ToInt32(e.CommandArgument);

                foreach (GridViewRow item in GridFileCarrinhoTransfers.Rows)
                {
                    TextBox txtQtdTarifas = (TextBox)item.FindControl("txtQtdTarifas");
                    Label IdFileTarifa = (Label)item.FindControl("IdFileTarifa");
                    TextBox txtValorTarifas = (TextBox)item.FindControl("txtValorTarifas");
                    TextBox txtVenda = (TextBox)item.FindControl("txtVenda");
                    TextBox txtVendaNet = (TextBox)item.FindControl("txtVendaNet");

                    if (IdTarifa == Convert.ToInt32(IdFileTarifa.Text))
                    {

                        File_Transfers ft = new File_Transfers();

                        double mult = Convert.ToDouble(txtVenda.Text) * Convert.ToDouble(txtQtdTarifas.Text);

                        double mkpNew = ((Convert.ToDouble(txtVenda.Text) / Convert.ToDouble(txtValorTarifas.Text)) * 100) - 100;

                        double vlNew = (Convert.ToDouble(txtVendaNet.Text) * mkpNew) / 100;

                        ft.S_merc_tarif_vendaNet = Convert.ToDecimal(vlNew) + Convert.ToDecimal(txtValorTarifas.Text);
                        ft.markup = Convert.ToDecimal(mkpNew);
                        ft.Transf_venda = Convert.ToDecimal(txtVenda.Text);
                        ft.Transf_total = Convert.ToDecimal(mult);
                        ft.File_Transf_id = IdTarifa;

                        ftd.AtualizarVenda(ft);
                    }

                }


                PopularGridListCarrinhoTransfers(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                MostrarMsg("File atualizado com sucesso.");
                CalculaValorTotal();

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }

        }

        protected void ExluirFileCarrinhoTransf(object sender, CommandEventArgs e)
        {
            try
            {

                int myid = Convert.ToInt32(e.CommandArgument);

                FileTransfersDAL ftd = new FileTransfersDAL();

                File_Transfers ft = ftd.ObterPorId(myid);

                ftd.Excluir(ft);


                MostrarMsg("Registro excluído com sucesso.");
                PopularGridListCarrinhoTransfers(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                CalculaValorTotal();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void VerTransfSubServicosAdicionados(object sender, CommandEventArgs e)
        {
            try
            {
                int myid = Convert.ToInt32(e.CommandArgument);

                MontaServicoDAL msd = new MontaServicoDAL();

                GridSubServPorTemporadaTrf.DataSource = msd.ListarTodosSubServicoPorTemporada(myid, Convert.ToInt32(ddlNumPaxTransfers.SelectedValue));
                GridSubServPorTemporadaTrf.DataBind();

                ModalPopupExtenderSubServAddTrf.Show();

            }
            catch (Exception ex)
            {

                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        protected void VerToursSubServicosAdicionados(object sender, CommandEventArgs e)
        {
            try
            {
                int myid = Convert.ToInt32(e.CommandArgument);

                MontaServicoDAL msd = new MontaServicoDAL();

                GridSubServPorTemporada.DataSource = msd.ListarTodosSubServicoPorTemporada(myid, Convert.ToInt32(ddlNumPaxsTours.SelectedValue));
                GridSubServPorTemporada.DataBind();

                ModalPopupExtenderSubServAdicionados.Show();

            }
            catch (Exception ex)
            {

                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        protected void OpenSubServicos(object sender, CommandEventArgs e)
        {
            try
            {

                string[] parms = Convert.ToString(e.CommandArgument).Split(',');

                string IdTrans = parms[0];
                string DataFrom = Convert.ToDateTime(parms[1]).ToShortDateString();
                string DataTo = Convert.ToDateTime(parms[2]).ToShortDateString();
                string PayPax = parms[3];

                ServicoCompletoFileDAL scfd = new ServicoCompletoFileDAL();

                Servico_Completo_File sc = scfd.ListarTodosPorTransf(Convert.ToInt32(IdTrans)).First();

                string script = "";
                script = script + "window.open('SubServicosCarrinhoNew.aspx?IdTrans=" + IdTrans + "&DataFrom=" + DataFrom + "&DataTo=" + DataTo + "&BaseIndex=" + Convert.ToInt32(sc.Base_Index) +
                                                                        "&IdServico=" + Convert.ToInt32(sc.Servicos_Id) + "&PayPax=" + PayPax + "','', " + "'status=1, scrollbars=yes, width=1160, height=580, top=0, left=0');";

                ScriptManager.RegisterStartupScript(this, this.GetType(), "Sub Serviços", script, true);
            }
            catch (Exception ex)
            {
                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void OpenSubServicosNewFile(object sender, CommandEventArgs e)
        {
            try
            {

                string[] parms = Convert.ToString(e.CommandArgument).Split(',');

                string IdTrans = parms[0];
                string DataFrom = Convert.ToDateTime(parms[1]).ToShortDateString();
                string DataTo = Convert.ToDateTime(parms[2]).ToShortDateString();
                string PayPax = parms[3];

                ServicoCompletoFileDAL scfd = new ServicoCompletoFileDAL();

                Servico_Completo_File sc = scfd.ListarTodosPorTransf(Convert.ToInt32(IdTrans)).First();

                string script = "";
                script = script + "window.open('SubServicosCarrinhoNew.aspx?IdTrans=" + IdTrans + "&DataFrom=" + DataFrom + "&DataTo=" + DataTo + "&BaseIndex=" + Convert.ToInt32(sc.Base_Index) +
                                                                        "&IdServico=" + Convert.ToInt32(sc.Servicos_Id) + "&PayPax=" + PayPax + "','', " + "'status=1, scrollbars=yes, width=1160, height=580, top=0, left=0');";

                ScriptManager.RegisterStartupScript(this, this.GetType(), "Sub Serviços", script, true);
            }
            catch (Exception ex)
            {
                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void OpenSubServicosNewFilePorBase(object sender, ImageClickEventArgs e)
        {
            try
            {
                string script = "";

                if (Convert.ToInt32(ViewState["TarifaFile"]) == 0)
                {
                    string[] parms = ViewState["DadosOpenSubServicos"].ToString().Split(',');

                    RangeDal rd = new RangeDal();
                    FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                    string IdTrans = "";
                    int IdQuote = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));

                    if (parms[6].Equals("TC"))
                    {
                        string[] titulo2 = GridBasesTarifas.HeaderRow.Cells[Convert.ToInt32(parms[8]) - 1].Text.ToString().Split('/');
                        Ranges er = rd.ObterPorTarifa(Convert.ToInt32(parms[1]), titulo2[0], titulo2[1], parms[2]);
                        Ranges r2 = rd.ObterPorIdID(er.Ranges_id);
                        IdTrans = r2.Ranges_id.ToString();
                    }
                    else
                    {
                        IdTrans = rd.ObterPorTarifa(IdQuote, Convert.ToInt32(parms[1]), parms[6], parms[7], parms[2]).Ranges_id.ToString();
                    }

                    string DataFrom = Convert.ToDateTime(parms[3]).ToShortDateString();
                    string DataTo = Convert.ToDateTime(parms[4]).ToShortDateString();
                    string PayPax = parms[6] + "/" + parms[7];//parms[3];

                    script = script + "window.open('SubServicosCarrinhoNew.aspx?Type=Q&IdTrans=" + IdTrans + "&DataFrom=" + DataFrom + "&DataTo=" + DataTo + "&PayPax=" + PayPax + "','', " + "'status=1, scrollbars=yes, width=1160, height=580, top=0, left=0');";
                }
                else
                {
                    string[] parms = ViewState["DadosOpenSubServicos"].ToString().Split(',');

                    Quote_Transf qtr = new QuoteTransDAL().ObterPorId(Convert.ToInt32(parms[1]));

                    string IdTrans = qtr.Quote_Transf_id.ToString();

                    string DataFrom = Convert.ToDateTime(qtr.Data_From).ToShortDateString();
                    string DataTo = Convert.ToDateTime(qtr.Data_To).ToShortDateString();
                    string PayPax = qtr.Paying_Pax + "/" + qtr.Paying_Pax;

                    script = script + "window.open('SubServicosCarrinhoNew.aspx?Type=F&IdTrans=" + IdTrans + "&DataFrom=" + DataFrom + "&DataTo=" + DataTo + "&PayPax=" + PayPax + "','', " + "'status=1, scrollbars=yes, width=1160, height=580, top=0, left=0');";
                }


                ScriptManager.RegisterStartupScript(this, this.GetType(), "Sub Serviços", script, true);
            }
            catch (Exception ex)
            {
                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void ddlSuppliersTransPorCidade_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                MontaServicoDAL msd = new MontaServicoDAL();

                ddlTransfersPorSupplier.DataSource = msd.ListarNomeTranfers(Convert.ToInt32(ViewState["IdCidadeTransfer"]), Convert.ToDateTime(txtDataFromTrans.Text), Convert.ToDateTime(txtDataToTrans.Text), Convert.ToInt32(ddlSuppliersTransPorCidade.SelectedValue), Convert.ToInt32(ddlNumPaxTransfers.SelectedValue));
                ddlTransfersPorSupplier.DataValueField = "Servicos_Id";
                ddlTransfersPorSupplier.DataTextField = "Servicos_Nome";
                ddlTransfersPorSupplier.DataBind();

                ddlTransfersPorSupplier.Items.Insert(0, new ListItem("Selecione...", "0"));
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void ddlNumPaxTransfers_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulaDataLisTransfers();
            PopulaDataLisTransfersSubServicos();
        }

        #endregion

        #region Files Tours Carrinho

        protected void btnSearchTours_Click(object sender, EventArgs e)
        {
            PopulaDataLisTours();
            PopulaDataLisToursSubServicos();
        }

        protected void BtnAddToursFileSub(object sender, CommandEventArgs e)
        {
            if (rdoOptFileTours.SelectedValue.Equals("0"))
            {
                btnAddTourFileSubNew(Convert.ToInt32(e.CommandArgument));
            }
            else
            {
                btnAddTourFileSubNewDirFile(Convert.ToInt32(e.CommandArgument));
            }
            //btnAddToursFileSub_Click(sender, e);
        }

        protected void btnAddToursFileSub_Click(object sender, CommandEventArgs e)
        {
            try
            {

                FileTransfersDAL ftd = new FileTransfersDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                ClienteDAL cli = new ClienteDAL();

                ClienteMarkupDAL climark = new ClienteMarkupDAL();

                HolidaysDAL hdal = new HolidaysDAL();
                HolidaysDatesDAL hdatesdal = new HolidaysDatesDAL();

                //decimal markupcliente = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_servico);
                //decimal markupdesconto = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_descontoServico);

                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToDateTime(txtDataFromTours.Text));
                decimal markupcliente = 0, markupdesconto = 0;
                if (mkfile != null)
                {
                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                    markupdesconto = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                }
                else
                {
                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(Convert.ToDateTime(txtDataFromTours.Text));

                    if (mgfile != null)
                    {
                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                        markupdesconto = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                    }
                    else
                    {
                        MostrarMsg("Não existe Markup cadastrado.");
                        return;
                    }
                }

                if (fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])) == null)
                {
                    File_Carrinho fc = new File_Carrinho();

                    fc.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                    fcd.Salvar(fc);
                }

                foreach (DataListItem item in DataListToursSubServicos.Items)
                {

                    if (item.ItemIndex == Convert.ToInt32(e.CommandArgument))
                    {

                        //btnAddTourFileSubNew(Convert.ToInt32(e.CommandArgument));

                        Label lblTituloTransfer = (Label)item.FindControl("lblTituloTransfer");
                        Label lblSupplierNome = (Label)item.FindControl("lblSupplierNome");
                        Label lblTarifaTotal = (Label)item.FindControl("lblTarifaTotal");
                        Label lblMoeda0 = (Label)item.FindControl("lblMoeda0");
                        Label lblMoedaId = (Label)item.FindControl("lblMoedaId");
                        Label lblSuplID = (Label)item.FindControl("lblSuplID");
                        Label lblIdMServicoTemporada = (Label)item.FindControl("lblIdMServicoTemporada");

                        File_Transfers ft = new File_Transfers();
                        MoedaDAL mod = new MoedaDAL();
                        CambioDAL cambDal = new CambioDAL();

                        MontaServicoDAL msd = new MontaServicoDAL();

                        ServicoDAL servd = new ServicoDAL();
                        S_Servicos ss = servd.ObterPorNome(lblTituloTransfer.Text);

                        if (hdal.VerificaHoliday(Convert.ToDateTime(txtDataFromTours.Text), ss.Servicos_Id) ||
                            hdal.VerificaHolidayEntreDatas(Convert.ToDateTime(txtDataFromTours.Text), ss.Servicos_Id) ||
                            hdal.VerificaHolidaySemana(Convert.ToDateTime(txtDataFromTours.Text), ss.Servicos_Id))
                        {
                            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "AlertarHolidays()", true);
                            return;
                        }

                        if (lblMoedaId.Text != ddlMoeda.SelectedValue)
                        {
                            Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(lblMoedaId.Text), Convert.ToInt32(ddlMoeda.SelectedValue));

                            decimal valor = Convert.ToDecimal(lblTarifaTotal.Text);

                            decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                            ft.Transf_valor = valorComCambio;
                        }
                        else
                        {
                            ft.Transf_valor = Convert.ToDecimal(lblTarifaTotal.Text);
                        }

                        ft.Paxs = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                        ft.Paying_Pax = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                        ft.Supp_Paying_Pax = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);

                        int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                        ft.Ordem = Ordem;

                        ft.Trf_CID_id = ObterIdCidadeServico(lblTituloTransfer.Text); //Convert.ToInt32(dllCidadeToursFiltro.SelectedValue);

                        ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                        ft.S_nome = lblSupplierNome.Text;
                        ft.Transf_nome = lblTituloTransfer.Text;
                        ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;
                        ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);

                        SupplierDAL sd = new SupplierDAL();

                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        {

                            //SupplierDAL sd = new SupplierDAL();
                            MarkupPaisDAL mkd = new MarkupPaisDAL();

                            Supplier spp = sd.ObterPorId(Convert.ToInt32(lblSuplID.Text));
                            MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                            ft.markup = mkp.MarkupServ;
                            ft.desconto = mkp.Desconto;
                            ft.markupNet = markupcliente;
                            ft.descontoNet = markupdesconto;
                        }
                        else
                        {
                            ft.markup = markupcliente;
                            ft.desconto = markupdesconto;
                            ft.markupNet = 0;
                            ft.descontoNet = 0;
                        }

                        //ft.markup = markupcliente;
                        //ft.desconto = markupdesconto;


                        ft.Qtd_Transf = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                        ft.Data_From = Convert.ToDateTime(txtDataFromTours.Text);
                        ft.Data_To = Convert.ToDateTime(txtDataToTours.Text);
                        ft.Trf_Tours = "TRS";
                        ft.Status = "OR";
                        ft.S_id = Convert.ToInt32(lblSuplID.Text);
                        ft.SubServico = true;
                        ft.FTC = false;

                        ftd.Salvar(ft);

                        ServicoCompletoFileDAL scfd = new ServicoCompletoFileDAL();

                        foreach (Servico_Completo scP in msd.ListarTodosSubServicoPorTemporadaLista(Convert.ToInt32(lblIdMServicoTemporada.Text), Convert.ToInt32(ddlNumPaxsTours.SelectedValue)))
                        {
                            Servico_Completo_File scf = new Servico_Completo_File();

                            scf.IdMServico = scP.IdMServico;
                            scf.File_Transf_id = ft.File_Transf_id;
                            scf.Base_Index = scP.Base_Index;
                            scf.Servicos_Id = scP.Servicos_Id;
                            scf.ServicoCompleto_de = scP.ServicoCompleto_de;
                            scf.ServicoCompleto_ate = scP.ServicoCompleto_ate;

                            int IdBase = scfd.ObterIdBase(Convert.ToInt32(scP.IdMServico), Convert.ToInt32(scP.ServicoCompleto_de), Convert.ToInt32(scP.Base_Index)).Base_id;

                            scf.SupplierID = sd.RetornaPorMServicoValores(Convert.ToInt32(scP.IdMServico), IdBase).S_id;

                            SBasesDAL sbd = new SBasesDAL();
                            int IdMoedaValor = sbd.ObterPorId(IdBase).Moeda_id;

                            if (IdMoedaValor != Convert.ToInt32(ddlMoeda.SelectedValue))
                            {
                                Cambio camb = cambDal.ObterPorIdMoedaPara(IdMoedaValor, Convert.ToInt32(ddlMoeda.SelectedValue));

                                decimal valor = Convert.ToDecimal(scfd.ObterValor(Convert.ToInt32(scP.IdMServico), IdBase).MServico_Valores_Bulk_Total);

                                decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                                scf.Valor = valorComCambio;
                            }
                            else
                            {
                                scf.Valor = scfd.ObterValor(Convert.ToInt32(scP.IdMServico), IdBase).MServico_Valores_Bulk_Total;
                            }

                            scfd.Salvar(scf);
                        }
                    }
                }

                PopularGridListCarrinhoTransfers(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                CalculaValorTotal();
                MostrarMsg("Tour adicionado ao file com sucesso.");

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void BtnAddToursFile(object sender, CommandEventArgs e)
        {
            if (rdoOptFileTours.SelectedValue.Equals("0"))
            {
                btnAddTourFileNew(Convert.ToInt32(e.CommandArgument));
            }
            else
            {
                btnAddTourFileNewDirFile(Convert.ToInt32(e.CommandArgument));
            }
            //btnAddToursFile_Click(sender, e);
        }

        protected void btnAddToursFile_Click(object sender, CommandEventArgs e)
        {
            try
            {

                FileTransfersDAL ftd = new FileTransfersDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                ClienteDAL cli = new ClienteDAL();

                HolidaysDAL hdal = new HolidaysDAL();
                HolidaysDatesDAL hdatesdal = new HolidaysDatesDAL();

                ClienteMarkupDAL climark = new ClienteMarkupDAL();

                //decimal markupcliente = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_servico);
                //decimal markupdesconto = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_descontoServico);

                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToDateTime(txtDataFromTours.Text));
                decimal markupcliente = 0, markupdesconto = 0;
                if (mkfile != null)
                {
                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                    markupdesconto = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                }
                else
                {
                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(Convert.ToDateTime(txtDataFromTours.Text));

                    if (mgfile != null)
                    {
                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                        markupdesconto = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                    }
                    else
                    {
                        MostrarMsg("Não existe Markup cadastrado.");
                        return;
                    }
                }

                if (fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])) == null)
                {
                    File_Carrinho fc = new File_Carrinho();

                    fc.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                    fcd.Salvar(fc);
                }

                foreach (DataListItem item in DataListTours.Items)
                {

                    if (item.ItemIndex == Convert.ToInt32(e.CommandArgument))
                    {

                        //btnAddTourFileNew(Convert.ToInt32(e.CommandArgument));

                        Label lblTituloTransfer = (Label)item.FindControl("lblTituloTransfer");
                        Label lblSupplierNome = (Label)item.FindControl("lblSupplierNome");
                        Label lblTarifaTotal = (Label)item.FindControl("lblTarifaTotal");
                        Label lblMoeda0 = (Label)item.FindControl("lblMoeda0");
                        Label lblMoedaId = (Label)item.FindControl("lblMoedaId");
                        Label lblSuplID = (Label)item.FindControl("lblSuplID");

                        File_Transfers ft = new File_Transfers();
                        MoedaDAL mod = new MoedaDAL();
                        CambioDAL cambDal = new CambioDAL();

                        ServicoDAL servd = new ServicoDAL();
                        S_Servicos ss = servd.ObterPorNome(lblTituloTransfer.Text);

                        if (hdal.VerificaHoliday(Convert.ToDateTime(txtDataFromTours.Text), ss.Servicos_Id) ||
                            hdal.VerificaHolidayEntreDatas(Convert.ToDateTime(txtDataFromTours.Text), ss.Servicos_Id) ||
                            hdal.VerificaHolidaySemana(Convert.ToDateTime(txtDataFromTours.Text), ss.Servicos_Id))
                        {
                            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "AlertarHolidays()", true);
                            return;
                        }

                        if (lblMoedaId.Text != ddlMoeda.SelectedValue)
                        {
                            Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(lblMoedaId.Text), Convert.ToInt32(ddlMoeda.SelectedValue));

                            decimal valor = Convert.ToDecimal(lblTarifaTotal.Text);

                            decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                            ft.Transf_valor = valorComCambio;
                        }
                        else
                        {
                            ft.Transf_valor = Convert.ToDecimal(lblTarifaTotal.Text);
                        }

                        ft.Paxs = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                        ft.Paying_Pax = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                        ft.Supp_Paying_Pax = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);

                        int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                        ft.Ordem = Ordem;

                        ft.Trf_CID_id = ObterIdCidadeServico(lblTituloTransfer.Text); //Convert.ToInt32(dllCidadeToursFiltro.SelectedValue);

                        ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                        ft.S_nome = lblSupplierNome.Text;
                        ft.Transf_nome = lblTituloTransfer.Text;
                        ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;
                        ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);


                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        {

                            SupplierDAL sd = new SupplierDAL();
                            MarkupPaisDAL mkd = new MarkupPaisDAL();

                            Supplier spp = sd.ObterPorId(Convert.ToInt32(lblSuplID.Text));
                            MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                            ft.markup = mkp.MarkupServ;
                            ft.desconto = mkp.Desconto;
                            ft.markupNet = markupcliente;
                            ft.descontoNet = markupdesconto;
                        }
                        else
                        {
                            ft.markup = markupcliente;
                            ft.desconto = markupdesconto;
                            ft.markupNet = 0;
                            ft.descontoNet = 0;
                        }

                        //ft.markup = markupcliente;
                        //ft.desconto = markupdesconto;


                        //ft.Transf_valor = Convert.ToDecimal(lblTarifaTotal.Text);
                        ft.Qtd_Transf = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                        ft.Data_From = Convert.ToDateTime(txtDataFromTours.Text);
                        ft.Data_To = Convert.ToDateTime(txtDataToTours.Text);
                        ft.Trf_Tours = "TRS";
                        ft.Status = "OR";
                        ft.S_id = Convert.ToInt32(lblSuplID.Text);
                        ft.FTC = false;

                        ftd.Salvar(ft);
                    }
                }

                PopularGridListCarrinhoTransfers(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                CalculaValorTotal();
                MostrarMsg("Transfer adicionado ao file com sucesso.");

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void btnAddTourFileNew(int e)
        {
            try
            {
                FileTransfersDAL ftd = new FileTransfersDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                ClienteDAL cli = new ClienteDAL();
                RangeDal rd = new RangeDal();
                CidadeDAL cdal = new CidadeDAL();
                ServicoDAL sd = new ServicoDAL();

                File_Carrinho fcarr = fcd.RetornaFileObj(txtQuoteNumber.Text);

                if (fcarr != null)
                {
                    if (rd.ListarTodosGroup(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text))).Count() == 0)
                    {
                        if (txtBaseDeNew.Text.Equals("") || txtBaseAteNew.Text.Equals(""))
                        {
                            MostrarMsg("Selecione uma base inicial para o file.");
                            return;
                        }
                    }
                }

                //ClienteMarkupDAL climark = new ClienteMarkupDAL();
                //decimal markupcliente = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_servico);
                //decimal markupdesconto = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_descontoServico);

                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToDateTime(txtDataFromTours.Text));
                decimal markupcliente = 0, markupdesconto = 0;
                if (mkfile != null)
                {
                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                    markupdesconto = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                }
                else
                {
                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(Convert.ToDateTime(txtDataFromTours.Text));

                    if (mgfile != null)
                    {
                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                        markupdesconto = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                    }
                    else
                    {
                        MostrarMsg("Não existe Markup cadastrado.");
                        return;
                    }
                }

                if (fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])) == null)
                {
                    File_Carrinho fc = new File_Carrinho();

                    fc.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                    fcd.Salvar(fc);
                }

                foreach (DataListItem item in DataListTours.Items)
                {

                    if (item.ItemIndex == Convert.ToInt32(e))
                    {

                        Label lblTituloTransfer = (Label)item.FindControl("lblTituloTransfer");
                        Label lblSupplierNome = (Label)item.FindControl("lblSupplierNome");
                        Label lblTarifaTotal = (Label)item.FindControl("lblTarifaTotal");
                        Label lblMoeda0 = (Label)item.FindControl("lblMoeda0");
                        Label lblMoedaId = (Label)item.FindControl("lblMoedaId");
                        Label lblSuplID = (Label)item.FindControl("lblSuplID");

                        File_Transfers ft = new File_Transfers();
                        MoedaDAL mod = new MoedaDAL();

                        ft.Paxs = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                        ft.Paying_Pax = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                        ft.Supp_Paying_Pax = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);

                        int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                        ft.Ordem = Ordem;

                        //ft.Trf_CID_id = ObterIdCidadeServico(lblTituloTransfer.Text); //Convert.ToInt32(dllCidadeToursFiltro.SelectedValue);

                        if (cdal.ObterPorNome(txtAutoCidadeTours.Text) != null)
                        {
                            ft.Trf_CID_id = cdal.ObterPorNome(txtAutoCidadeTours.Text).CID_id;
                        }
                        else
                        {
                            if (sd.ObterPorNomeLista(lblTituloTransfer.Text).Count > 1)
                            {
                                Supplier suppp = new SupplierDAL().ObterSupplierPorNome(lblSupplierNome.Text);
                                if (suppp != null)
                                {
                                    ft.Trf_CID_id = suppp.CID_id;
                                }
                            }
                        }

                        ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                        ft.S_nome = lblSupplierNome.Text;
                        ft.Transf_nome = lblTituloTransfer.Text;
                        ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;
                        ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);

                        ft.Qtd_Transf = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                        ft.Data_From = Convert.ToDateTime(txtDataFromTours.Text);
                        ft.Data_To = Convert.ToDateTime(txtDataToTours.Text);
                        ft.Trf_Tours = "TRS";
                        ft.Status = "OR";
                        ft.S_id = Convert.ToInt32(lblSuplID.Text);
                        ft.FTC = false;

                        ft.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                        ftd.Salvar(ft);

                        File_Transfers ftrange = new File_Transfers();
                        ftrange.Range_id = 0;
                        ftrange.File_Transf_id = ft.File_Transf_id;

                        ftd.AtualizarRange(ftrange);

                        bool existe = rd.VerificaExisteRegOpt(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), Convert.ToInt32(ViewState["QuoteAtiva"]));

                        ViewState["IdTemporada"] = "";

                        //if (rd.ListarTodosGroup(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text))).Count() > 0)
                        if (existe)
                        {
                            SalvaRangesServicosExistentes("tour", false, Convert.ToInt32(lblSuplID.Text), markupcliente, markupdesconto, lblTituloTransfer.Text, Convert.ToInt32(lblMoedaId.Text), ft.File_Transf_id);
                        }
                        else
                        {
                            SalvaRangesServicosVazio("tour", false, Convert.ToInt32(lblSuplID.Text), markupcliente, markupdesconto, lblTituloTransfer.Text, Convert.ToInt32(lblMoedaId.Text), ft.File_Transf_id);
                        }

                        PopulaNewQuote(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToInt32(ViewState["QuoteAtiva"]));
                    }
                }

                MostrarMsg("Tarifas adicionadas ao file com sucesso.");
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void btnAddTourFileNewDirFile(int e)
        {
            try
            {

                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                ClienteDAL cli = new ClienteDAL();
                HolidaysDAL hdal = new HolidaysDAL();
                HolidaysDatesDAL hdatesdal = new HolidaysDatesDAL();
                CidadeDAL cdal = new CidadeDAL();

                QuoteTransDAL ftd = new QuoteTransDAL();

                Quotation q = fcd.RetornaQuoteObj(txtQuoteNumber.Text);
                if (q == null)
                {
                    if (txtBaseDeNew.Text.Equals("") || txtBaseAteNew.Text.Equals(""))
                    {
                        MostrarMsg("Selecione uma base inicial para o file.");
                        return;
                    }
                }

                ClienteMarkupDAL climark = new ClienteMarkupDAL();

                DateTime In = Convert.ToDateTime(txtDataFromTours.Text);
                DateTime Out = Convert.ToDateTime(txtDataToTours.Text);

                //Cliente_Markup cl = climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue));
                //decimal markupcliente = 0;
                //decimal markupdesconto = 0;
                //if (cl == null)
                //{
                //    MostrarMsg("Esse cliente não possui markup cadastrado.");
                //    return;
                //}
                //else
                //{
                //    markupcliente = Convert.ToDecimal(cl.Markup_hotel);
                //    markupdesconto = Convert.ToDecimal(cl.Markup_descontoHotel);
                //}

                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), In);
                decimal markupcliente = 0, markupdesconto = 0;
                if (mkfile != null)
                {
                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                    markupdesconto = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                }
                else
                {
                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(In);

                    if (mgfile != null)
                    {
                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                        markupdesconto = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                    }
                    else
                    {
                        MostrarMsg("Não existe Markup cadastrado.");
                        return;
                    }
                }

                if (fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])) == null)
                {
                    File_Carrinho fc = new File_Carrinho();

                    fc.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                    fcd.Salvar(fc);
                }

                foreach (DataListItem item in DataListTours.Items)
                {

                    if (item.ItemIndex == e)
                    {

                        Label lblTituloTransfer = (Label)item.FindControl("lblTituloTransfer");
                        Label lblSupplierNome = (Label)item.FindControl("lblSupplierNome");
                        Label lblTarifaTotal = (Label)item.FindControl("lblTarifaTotal");
                        Label lblMoeda0 = (Label)item.FindControl("lblMoeda0");
                        Label lblMoedaId = (Label)item.FindControl("lblMoedaId");
                        Label lblSuplID = (Label)item.FindControl("lblSuplID");

                        Quote_Transf ft = new Quote_Transf();
                        MoedaDAL mod = new MoedaDAL();
                        CambioDAL cambDal = new CambioDAL();

                        ServicoDAL servd = new ServicoDAL();
                        S_Servicos ss = servd.ObterPorNome(lblTituloTransfer.Text);

                        if (hdal.VerificaHoliday(Convert.ToDateTime(txtDataFromTours.Text), ss.Servicos_Id) ||
                            hdal.VerificaHolidayEntreDatas(Convert.ToDateTime(txtDataFromTours.Text), ss.Servicos_Id) ||
                            hdal.VerificaHolidaySemana(Convert.ToDateTime(txtDataFromTours.Text), ss.Servicos_Id))
                        {
                            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "AlertarHolidays()", true);
                            return;
                        }

                        if (lblMoedaId.Text != ddlMoeda.SelectedValue)
                        {
                            Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(lblMoedaId.Text), Convert.ToInt32(ddlMoeda.SelectedValue));

                            decimal valor = Convert.ToDecimal(lblTarifaTotal.Text);

                            decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                            ft.Transf_valor = valorComCambio;
                        }
                        else
                        {
                            ft.Transf_valor = Convert.ToDecimal(lblTarifaTotal.Text);
                        }

                        ft.Paxs = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                        ft.Paying_Pax = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                        ft.Supp_Paying_Pax = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);

                        int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                        ft.Ordem = Ordem;

                        //ft.Trf_CID_id = ObterIdCidadeServico(lblTituloTransfer.Text);
                        if (cdal.ObterPorNome(txtAutoCidadeTours.Text) != null)
                        {
                            ft.Trf_CID_id = cdal.ObterPorNome(txtAutoCidadeTours.Text).CID_id;
                        }
                        else
                        {
                            if (servd.ObterPorNomeLista(lblTituloTransfer.Text).Count > 1)
                            {
                                Supplier suppp = new SupplierDAL().ObterSupplierPorNome(lblSupplierNome.Text);
                                if (suppp != null)
                                {
                                    ft.Trf_CID_id = suppp.CID_id;
                                }
                            }
                        }

                        ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                        ft.S_nome = lblSupplierNome.Text;
                        ft.Transf_nome = lblTituloTransfer.Text;
                        ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;
                        ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);


                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        {

                            SupplierDAL sd = new SupplierDAL();
                            MarkupPaisDAL mkd = new MarkupPaisDAL();

                            Supplier spp = sd.ObterPorId(Convert.ToInt32(lblSuplID.Text));
                            MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                            ft.markup = mkp.MarkupServ;
                            ft.desconto = mkp.Desconto;
                            ft.markupNet = markupcliente;
                            ft.descontoNet = markupdesconto;
                        }
                        else
                        {
                            ft.markup = markupcliente;
                            ft.desconto = markupdesconto;
                            ft.markupNet = 0;
                            ft.descontoNet = 0;
                        }

                        ft.Qtd_Transf = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                        ft.Data_From = Convert.ToDateTime(txtDataFromTours.Text);
                        ft.Data_To = Convert.ToDateTime(txtDataToTours.Text);
                        ft.Trf_Tours = "TRS";
                        ft.Status = "OR";
                        ft.S_id = Convert.ToInt32(lblSuplID.Text);
                        ft.FTC = false;
                        ft.Flag = "servico";
                        ft.Range_id = 0;
                        if (flagTC == 0) ft.TC = false; else ft.TC = true;

                        ftd.Salvar(ft);

                        AcertaRangeDirFile(ft.Quote_Transf_id, "servico");
                        PopularNewFile();
                    }
                }

                if (flagTC == 0)
                {
                    if (fcd.VerificaExisteTCQuotes(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))))
                    {
                        flagTC = 1;
                        btnAddTourFileNewDirFile(e);
                    }
                }
                else
                {
                    flagTC = 0;
                }

                MostrarMsg("Transfer adicionado ao file com sucesso.");

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void btnAddTourFileSubNew(int e)
        {
            try
            {

                FileTransfersDAL ftd = new FileTransfersDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                ClienteDAL cli = new ClienteDAL();
                RangeDal rd = new RangeDal();
                CidadeDAL cdal = new CidadeDAL();
                ServicoDAL sd = new ServicoDAL();

                File_Carrinho fcarr = fcd.RetornaFileObj(txtQuoteNumber.Text);

                if (fcarr != null)
                {
                    if (rd.ListarTodosGroup(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text))).Count() == 0)
                    {
                        if (txtBaseDeNew.Text.Equals("") || txtBaseAteNew.Text.Equals(""))
                        {
                            MostrarMsg("Selecione uma base inicial para o file.");
                            return;
                        }
                    }
                }

                //ClienteMarkupDAL climark = new ClienteMarkupDAL();
                //decimal markupcliente = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_servico);
                //decimal markupdesconto = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_descontoServico);

                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToDateTime(txtDataFromTours.Text));
                decimal markupcliente = 0, markupdesconto = 0;
                if (mkfile != null)
                {
                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                    markupdesconto = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                }
                else
                {
                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(Convert.ToDateTime(txtDataFromTours.Text));

                    if (mgfile != null)
                    {
                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                        markupdesconto = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                    }
                    else
                    {
                        MostrarMsg("Não existe Markup cadastrado.");
                        return;
                    }
                }

                if (fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])) == null)
                {
                    File_Carrinho fc = new File_Carrinho();

                    fc.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                    fcd.Salvar(fc);
                }

                foreach (DataListItem item in DataListToursSubServicos.Items)
                {

                    if (item.ItemIndex == Convert.ToInt32(e))
                    {

                        Label lblTituloTransfer = (Label)item.FindControl("lblTituloTransfer");
                        Label lblSupplierNome = (Label)item.FindControl("lblSupplierNome");
                        Label lblTarifaTotal = (Label)item.FindControl("lblTarifaTotal");
                        Label lblMoeda0 = (Label)item.FindControl("lblMoeda0");
                        Label lblMoedaId = (Label)item.FindControl("lblMoedaId");
                        Label lblSuplID = (Label)item.FindControl("lblSuplID");
                        Label lblIdMServicoTemporada = (Label)item.FindControl("lblIdMServicoTemporada");

                        File_Transfers ft = new File_Transfers();
                        MoedaDAL mod = new MoedaDAL();

                        MontaServicoDAL msd = new MontaServicoDAL();

                        ft.Paxs = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                        ft.Paying_Pax = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                        ft.Supp_Paying_Pax = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);

                        int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                        ft.Ordem = Ordem;

                        //ft.Trf_CID_id = ObterIdCidadeServico(lblTituloTransfer.Text); //Convert.ToInt32(dllCidadeToursFiltro.SelectedValue);
                        if (cdal.ObterPorNome(txtAutoCidadeTours.Text) != null)
                        {
                            ft.Trf_CID_id = cdal.ObterPorNome(txtAutoCidadeTours.Text).CID_id;
                        }
                        else
                        {
                            if (sd.ObterPorNomeLista(lblTituloTransfer.Text).Count > 1)
                            {
                                Supplier suppp = new SupplierDAL().ObterSupplierPorNome(lblSupplierNome.Text);
                                if (suppp != null)
                                {
                                    ft.Trf_CID_id = suppp.CID_id;
                                }
                            }
                        }

                        ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                        ft.S_nome = lblSupplierNome.Text;
                        ft.Transf_nome = lblTituloTransfer.Text;
                        ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;
                        ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);

                        ft.Qtd_Transf = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                        ft.Data_From = Convert.ToDateTime(txtDataFromTours.Text);
                        ft.Data_To = Convert.ToDateTime(txtDataToTours.Text);
                        ft.Trf_Tours = "TRS";
                        ft.Status = "OR";
                        ft.S_id = Convert.ToInt32(lblSuplID.Text);
                        ft.SubServico = true;
                        ft.FTC = false;

                        ft.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                        ftd.Salvar(ft);

                        File_Transfers ftrange = new File_Transfers();
                        ftrange.Range_id = 0;
                        ftrange.File_Transf_id = ft.File_Transf_id;

                        ftd.AtualizarRange(ftrange);

                        bool existe = rd.VerificaExisteRegOpt(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), Convert.ToInt32(ViewState["QuoteAtiva"]));
                        ViewState["IdTemporada"] = lblIdMServicoTemporada.Text;

                        //if (rd.ListarTodosGroup(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text))).Count() > 0)
                        if (existe)
                        {
                            SalvaRangesServicosExistentes("tour", true, Convert.ToInt32(lblSuplID.Text), markupcliente, markupdesconto, lblTituloTransfer.Text, Convert.ToInt32(lblMoedaId.Text), ft.File_Transf_id);
                        }
                        else
                        {
                            SalvaRangesServicosVazio("tour", true, Convert.ToInt32(lblSuplID.Text), markupcliente, markupdesconto, lblTituloTransfer.Text, Convert.ToInt32(lblMoedaId.Text), ft.File_Transf_id);
                        }

                        PopulaNewQuote(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToInt32(ViewState["QuoteAtiva"]));

                        ServicoCompletoFileDAL scfd = new ServicoCompletoFileDAL();
                        CambioDAL cambDal = new CambioDAL();

                        foreach (Servico_Completo scP in msd.ListarTodosSubServicoPorTemporadaLista(Convert.ToInt32(lblIdMServicoTemporada.Text), Convert.ToInt32(ddlNumPaxsTours.SelectedValue)))
                        {
                            Servico_Completo_File scf = new Servico_Completo_File();

                            scf.IdMServico = scP.IdMServico;
                            scf.File_Transf_id = ft.File_Transf_id;
                            scf.Base_Index = scP.Base_Index;
                            scf.Servicos_Id = scP.Servicos_Id;
                            scf.ServicoCompleto_de = scP.ServicoCompleto_de;
                            scf.ServicoCompleto_ate = scP.ServicoCompleto_ate;

                            int IdBase = scfd.ObterIdBase(Convert.ToInt32(scP.IdMServico), Convert.ToInt32(scP.ServicoCompleto_de), Convert.ToInt32(scP.Base_Index)).Base_id;

                            SBasesDAL sbd = new SBasesDAL();
                            int IdMoedaValor = sbd.ObterPorId(IdBase).Moeda_id;

                            if (IdMoedaValor != Convert.ToInt32(ddlMoeda.SelectedValue))
                            {
                                Cambio camb = cambDal.ObterPorIdMoedaPara(IdMoedaValor, Convert.ToInt32(ddlMoeda.SelectedValue));

                                decimal valor = Convert.ToDecimal(scfd.ObterValor(Convert.ToInt32(scP.IdMServico), IdBase).MServico_Valores_Bulk_Total);

                                decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                                scf.Valor = valorComCambio;
                            }
                            else
                            {
                                scf.Valor = scfd.ObterValor(Convert.ToInt32(scP.IdMServico), IdBase).MServico_Valores_Bulk_Total;
                            }

                            scfd.Salvar(scf);
                        }
                    }
                }

                MostrarMsg("Tarifas adicionadas ao file com sucesso.");
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void btnAddTourFileSubNewDirFile(int e)
        {
            try
            {

                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                ClienteDAL cli = new ClienteDAL();
                HolidaysDAL hdal = new HolidaysDAL();
                HolidaysDatesDAL hdatesdal = new HolidaysDatesDAL();
                CidadeDAL cdal = new CidadeDAL();


                QuoteTransDAL ftd = new QuoteTransDAL();

                Quotation q = fcd.RetornaQuoteObj(txtQuoteNumber.Text);
                if (q == null)
                {
                    if (txtBaseDeNew.Text.Equals("") || txtBaseAteNew.Text.Equals(""))
                    {
                        MostrarMsg("Selecione uma base inicial para o file.");
                        return;
                    }
                }

                ClienteMarkupDAL climark = new ClienteMarkupDAL();

                DateTime In = Convert.ToDateTime(txtDataFromTours.Text);
                DateTime Out = Convert.ToDateTime(txtDataToTours.Text);

                //Cliente_Markup cl = climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue));
                //decimal markupcliente = 0;
                //decimal markupdesconto = 0;
                //if (cl == null)
                //{
                //    MostrarMsg("Esse cliente não possui markup cadastrado.");
                //    return;
                //}
                //else
                //{
                //    markupcliente = Convert.ToDecimal(cl.Markup_hotel);
                //    markupdesconto = Convert.ToDecimal(cl.Markup_descontoHotel);
                //}

                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), In);
                decimal markupcliente = 0, markupdesconto = 0;
                if (mkfile != null)
                {
                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                    markupdesconto = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                }
                else
                {
                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(In);

                    if (mgfile != null)
                    {
                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                        markupdesconto = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                    }
                    else
                    {
                        MostrarMsg("Não existe Markup cadastrado.");
                        return;
                    }
                }

                if (fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])) == null)
                {
                    File_Carrinho fc = new File_Carrinho();

                    fc.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                    fcd.Salvar(fc);
                }

                foreach (DataListItem item in DataListToursSubServicos.Items)
                {

                    if (item.ItemIndex == e)
                    {

                        Label lblTituloTransfer = (Label)item.FindControl("lblTituloTransfer");
                        Label lblSupplierNome = (Label)item.FindControl("lblSupplierNome");
                        Label lblTarifaTotal = (Label)item.FindControl("lblTarifaTotal");
                        Label lblMoeda0 = (Label)item.FindControl("lblMoeda0");
                        Label lblMoedaId = (Label)item.FindControl("lblMoedaId");
                        Label lblSuplID = (Label)item.FindControl("lblSuplID");
                        Label lblIdMServicoTemporada = (Label)item.FindControl("lblIdMServicoTemporada");

                        Quote_Transf ft = new Quote_Transf();
                        MoedaDAL mod = new MoedaDAL();
                        CambioDAL cambDal = new CambioDAL();

                        MontaServicoDAL msd = new MontaServicoDAL();

                        ServicoDAL servd = new ServicoDAL();
                        S_Servicos ss = servd.ObterPorNome(lblTituloTransfer.Text);

                        if (hdal.VerificaHoliday(Convert.ToDateTime(txtDataFromTours.Text), ss.Servicos_Id) ||
                            hdal.VerificaHolidayEntreDatas(Convert.ToDateTime(txtDataFromTours.Text), ss.Servicos_Id) ||
                            hdal.VerificaHolidaySemana(Convert.ToDateTime(txtDataFromTours.Text), ss.Servicos_Id))
                        {
                            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "AlertarHolidays()", true);
                            return;
                        }

                        if (lblMoedaId.Text != ddlMoeda.SelectedValue)
                        {
                            Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(lblMoedaId.Text), Convert.ToInt32(ddlMoeda.SelectedValue));

                            decimal valor = Convert.ToDecimal(lblTarifaTotal.Text);

                            decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                            ft.Transf_valor = valorComCambio;
                        }
                        else
                        {
                            ft.Transf_valor = Convert.ToDecimal(lblTarifaTotal.Text);
                        }

                        ft.Paxs = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                        ft.Paying_Pax = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                        ft.Supp_Paying_Pax = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);

                        int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                        ft.Ordem = Ordem;

                        //ft.Trf_CID_id = ObterIdCidadeServico(lblTituloTransfer.Text); //Convert.ToInt32(dllCidadeToursFiltro.SelectedValue);
                        if (cdal.ObterPorNome(txtAutoCidadeTours.Text) != null)
                        {
                            ft.Trf_CID_id = cdal.ObterPorNome(txtAutoCidadeTours.Text).CID_id;
                        }
                        else
                        {
                            if (servd.ObterPorNomeLista(lblTituloTransfer.Text).Count > 1)
                            {
                                Supplier suppp = new SupplierDAL().ObterSupplierPorNome(lblSupplierNome.Text);
                                if (suppp != null)
                                {
                                    ft.Trf_CID_id = suppp.CID_id;
                                }
                            }
                        }

                        ft.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                        ft.S_nome = lblSupplierNome.Text;
                        ft.Transf_nome = lblTituloTransfer.Text;
                        ft.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;
                        ft.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);

                        SupplierDAL sd = new SupplierDAL();

                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        {
                            MarkupPaisDAL mkd = new MarkupPaisDAL();

                            Supplier spp = sd.ObterPorId(Convert.ToInt32(lblSuplID.Text));
                            MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                            ft.markup = mkp.MarkupServ;
                            ft.desconto = mkp.Desconto;
                            ft.markupNet = markupcliente;
                            ft.descontoNet = markupdesconto;
                        }
                        else
                        {
                            ft.markup = markupcliente;
                            ft.desconto = markupdesconto;
                            ft.markupNet = 0;
                            ft.descontoNet = 0;
                        }

                        ft.Qtd_Transf = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                        ft.Data_From = Convert.ToDateTime(txtDataFromTours.Text);
                        ft.Data_To = Convert.ToDateTime(txtDataToTours.Text);
                        ft.Trf_Tours = "TRS";
                        ft.Status = "OR";
                        ft.S_id = Convert.ToInt32(lblSuplID.Text);
                        ft.SubServico = true;
                        ft.FTC = false;
                        ft.Flag = "servico";
                        ft.Range_id = 0;
                        if (flagTC == 0) ft.TC = false; else ft.TC = true;

                        ftd.Salvar(ft);

                        SubServicosFileDAL ssfdal = new SubServicosFileDAL();
                        MontaServicoDAL mserdal = new MontaServicoDAL();

                        Array tes = mserdal.ListarTodosSubServicoPorTemporadaArray(Convert.ToInt32(lblIdMServicoTemporada.Text), Convert.ToInt32(ft.Paying_Pax));

                        foreach (var arr in tes)
                        {
                            string[] separators = { ", ", "=", "{", "}" };
                            string value = arr.ToString();
                            string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);

                            SubServicosFile ssf = new SubServicosFile();
                            ssf.NomeSupplier = words[1].Trim();
                            ssf.ServDe = ft.Paying_Pax.ToString();
                            ssf.ServAte = ft.Paying_Pax.ToString();
                            ssf.NomeFantasia = words[9].Trim();
                            ssf.NomeSubItem = words[11].Trim();
                            //ssf.Moeda_id = Convert.ToInt32(words[13]);
                            //ssf.Moeda = words[15].Trim();

                            decimal val = 0;
                            if (Convert.ToInt32(words[17]) == 1)
                                val = Convert.ToDecimal(words[7]) / Convert.ToDecimal(ft.Paying_Pax.ToString());
                            else
                                val = Convert.ToDecimal(words[7]);

                            if (Convert.ToInt32(words[13]).ToString() != ddlMoeda.SelectedValue)
                            {
                                Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(words[13]), Convert.ToInt32(ddlMoeda.SelectedValue));
                                decimal valorComCambio = val * Convert.ToDecimal(camb.Cambio1);
                                ssf.Valor = valorComCambio;
                            }
                            else ssf.Valor = val;

                            ssf.Quote_Transf_id = ft.Quote_Transf_id;

                            ssfdal.Salvar(ssf);
                        }

                        AcertaRangeDirFile(ft.Quote_Transf_id, "servico");
                        PopularNewFile();

                        ServicoCompletoFileDAL scfd = new ServicoCompletoFileDAL();

                        foreach (Servico_Completo scP in msd.ListarTodosSubServicoPorTemporadaLista(Convert.ToInt32(lblIdMServicoTemporada.Text), Convert.ToInt32(ddlNumPaxsTours.SelectedValue)))
                        {
                            Servico_Completo_File scf = new Servico_Completo_File();

                            scf.IdMServico = scP.IdMServico;
                            scf.Quote_Transf_id = ft.Quote_Transf_id;
                            scf.Base_Index = scP.Base_Index;
                            scf.Servicos_Id = scP.Servicos_Id;
                            scf.ServicoCompleto_de = scP.ServicoCompleto_de;
                            scf.ServicoCompleto_ate = scP.ServicoCompleto_ate;

                            int IdBase = scfd.ObterIdBase(Convert.ToInt32(scP.IdMServico), Convert.ToInt32(scP.ServicoCompleto_de), Convert.ToInt32(scP.Base_Index)).Base_id;

                            scf.SupplierID = sd.RetornaPorMServicoValores(Convert.ToInt32(scP.IdMServico), IdBase).S_id;

                            SBasesDAL sbd = new SBasesDAL();
                            int IdMoedaValor = sbd.ObterPorId(IdBase).Moeda_id;

                            if (IdMoedaValor != Convert.ToInt32(ddlMoeda.SelectedValue))
                            {
                                Cambio camb = cambDal.ObterPorIdMoedaPara(IdMoedaValor, Convert.ToInt32(ddlMoeda.SelectedValue));

                                decimal valor = Convert.ToDecimal(scfd.ObterValor(Convert.ToInt32(scP.IdMServico), IdBase).MServico_Valores_Bulk_Total);

                                decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                                scf.Valor = valorComCambio;
                            }
                            else
                            {
                                scf.Valor = scfd.ObterValor(Convert.ToInt32(scP.IdMServico), IdBase).MServico_Valores_Bulk_Total;
                            }

                            scfd.Salvar(scf);
                        }
                    }
                }

                if (flagTC == 0)
                {
                    if (fcd.VerificaExisteTCQuotes(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))))
                    {
                        flagTC = 1;
                        btnAddTourFileSubNewDirFile(e);
                    }
                }
                else
                {
                    flagTC = 0;
                }

                MostrarMsg("Tour adicionado ao file com sucesso.");

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void ddlSupplierToursFiltro_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                MontaServicoDAL msd = new MontaServicoDAL();

                ddlToursPorSupplier.DataSource = msd.ListarNomeTours(Convert.ToInt32(ViewState["IdCidadeTour"]), Convert.ToDateTime(txtDataFromTours.Text), Convert.ToDateTime(txtDataToTours.Text), Convert.ToInt32(ddlSupplierToursFiltro.SelectedValue), Convert.ToInt32(ddlNumPaxsTours.SelectedValue));
                ddlToursPorSupplier.DataValueField = "Servicos_Id";
                ddlToursPorSupplier.DataTextField = "Servicos_Nome";
                ddlToursPorSupplier.DataBind();

                ddlToursPorSupplier.Items.Insert(0, new ListItem("Selecione...", "0"));
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void ddlNumPaxsTours_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulaDataLisTours();
            PopulaDataLisToursSubServicos();
        }

        #endregion

        #region Files Servico Extra

        [WebMethod]
        protected void btnAddServExtra_Click(object sender, EventArgs e)
        {
            if (statusServExtra.Equals("none"))
            {
                statusServExtra = "block";
                PopulaDropSuppliersServExtra();
                btnProcurarTours.Visible = false;
            }
            else
            {
                statusServExtra = "none";
                btnProcurarTours.Visible = true;
            }

            DataListToursSubServicos.DataBind();
            DataListTours.DataBind();
        }

        protected void BtnCadastrarServExtra(object sender, EventArgs e)
        {
            btnCadastrarServExtraByBases();
            //btnCadastrarServExtra_Click(sender, e);
        }

        protected void btnCadastrarServExtra_Click(object sender, EventArgs e)
        {
            try
            {
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                ClienteMarkupDAL climark = new ClienteMarkupDAL();

                //decimal markupcliente = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_servico);
                //decimal markupdesconto = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_descontoServico);

                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToDateTime(txtDataFromTours.Text));
                decimal markupcliente = 0, markupdesconto = 0;
                if (mkfile != null)
                {
                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                    markupdesconto = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                }
                else
                {
                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(Convert.ToDateTime(txtDataFromTours.Text));

                    if (mgfile != null)
                    {
                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                        markupdesconto = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                    }
                    else
                    {
                        MostrarMsg("Não existe Markup cadastrado.");
                        return;
                    }
                }

                //btnCadastrarServExtraByBases();

                if (fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])) == null)
                {
                    File_Carrinho fc = new File_Carrinho();

                    fc.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                    fcd.Salvar(fc);
                }

                File_ServExtra fs = new File_ServExtra();
                MoedaDAL mod = new MoedaDAL();

                fs.Paxs = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                fs.Paying_Pax = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                fs.Supp_Paying_Pax = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);

                fs.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                fs.Data_From = Convert.ToDateTime(txtDataFromTours.Text);
                fs.Data_To = Convert.ToDateTime(txtDataToTours.Text);
                fs.NumPaxs_ServExtr = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                fs.S_nome = ddlSuppliersServExtra.SelectedItem.Text;
                fs.S_id = Convert.ToInt32(ddlSuppliersServExtra.SelectedValue);
                fs.File_ServExtra_nome = txtNomeServExtra.Text;
                fs.TipoServico = ddlTipoServicoExtra.SelectedItem.Text;
                fs.TipoServico_id = Convert.ToInt32(ddlTipoServicoExtra.SelectedValue);
                fs.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);
                fs.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;
                fs.Status = "OR";
                fs.FTC = false;

                int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                fs.Ordem = Ordem;

                if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                {

                    SupplierDAL sd = new SupplierDAL();
                    MarkupPaisDAL mkd = new MarkupPaisDAL();

                    Supplier spp = sd.ObterPorId(Convert.ToInt32(ddlSuppliersServExtra.SelectedValue));
                    MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                    fs.markup = mkp.MarkupServ;
                    fs.desconto = mkp.Desconto;
                    fs.markupNet = markupcliente;
                    fs.descontoNet = markupdesconto;
                }
                else
                {
                    fs.markup = markupcliente;
                    fs.desconto = markupdesconto;
                    fs.markupNet = 0;
                    fs.descontoNet = 0;
                }

                FileServExtraDAL fsd = new FileServExtraDAL();
                fsd.Salvar(fs);

                MostrarMsg("Registro cadastrado com sucesso.");

                txtNomeServExtra.Text = "";
                PopulaDropSuppliersServExtra();
                PopularddlTipoServExtra();

                PopularGridListCarrinhoExtras(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                CalculaValorTotal();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        protected void btnCadastrarServExtraByBases()
        {
            try
            {
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                ClienteMarkupDAL climark = new ClienteMarkupDAL();

                //decimal markupcliente = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_servico);
                //decimal markupdesconto = Convert.ToDecimal(climark.ObterPorIdCliente(Convert.ToInt32(ddlCliente.SelectedValue)).Markup_descontoServico);

                MarkupFile mkfile = new MarkupFileDAL().ObterPorQGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToDateTime(txtDataFromTours.Text));
                decimal markupcliente = 0, markupdesconto = 0;
                if (mkfile != null)
                {
                    markupcliente = Convert.ToDecimal(mkfile.MarkupFile_hotel);
                    markupdesconto = Convert.ToDecimal(mkfile.MarkupFile_descontoHotel);
                }
                else
                {
                    MarkupGeral mgfile = new MarkupGeralDAL().ObterPorAno(Convert.ToDateTime(txtDataFromTours.Text));

                    if (mgfile != null)
                    {
                        markupcliente = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                        markupdesconto = Convert.ToDecimal(mgfile.MarkupGeral_hotel);
                    }
                    else
                    {
                        MostrarMsg("Não existe Markup cadastrado.");
                        return;
                    }
                }

                if (fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])) == null)
                {
                    File_Carrinho fc = new File_Carrinho();

                    fc.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                    fcd.Salvar(fc);
                }

                RangeDal rd = new RangeDal();
                File_ServExtra fs = new File_ServExtra();
                MoedaDAL mod = new MoedaDAL();

                fs.Paxs = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                fs.Paying_Pax = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                fs.Supp_Paying_Pax = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);

                fs.File_id = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                fs.Data_From = Convert.ToDateTime(txtDataFromTours.Text);
                fs.Data_To = Convert.ToDateTime(txtDataToTours.Text);
                fs.NumPaxs_ServExtr = Convert.ToInt32(ddlNumPaxsTours.SelectedValue);
                fs.S_nome = ddlSuppliersServExtra.SelectedItem.Text;
                fs.S_id = Convert.ToInt32(ddlSuppliersServExtra.SelectedValue);
                fs.File_ServExtra_nome = txtNomeServExtra.Text;
                fs.TipoServico = ddlTipoServicoExtra.SelectedItem.Text;
                fs.TipoServico_id = Convert.ToInt32(ddlTipoServicoExtra.SelectedValue);
                fs.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);
                fs.Moeda = mod.ObterPorId(Convert.ToInt32(ddlMoeda.SelectedValue)).Moeda_sigla;
                fs.Status = "OR";
                fs.FTC = false;

                int Ordem = RetornaUltimaOrdem(fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]))) + 1;

                fs.Ordem = Ordem;

                fs.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                FileServExtraDAL fsd = new FileServExtraDAL();
                fsd.Salvar(fs);

                File_ServExtra ftrange = new File_ServExtra();
                ftrange.Range_id = 0;
                ftrange.File_ServExtra_id = fs.File_ServExtra_id;

                fsd.AtualizarRange(ftrange);

                if (rd.ListarTodosGroup(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text))).Count() > 0)
                {
                    SalvaRangesSerExtraExistentes(Convert.ToDateTime(txtDataFromTours.Text), Convert.ToDateTime(txtDataToTours.Text), markupcliente, markupdesconto, Convert.ToInt32(ddlSuppliersServExtra.SelectedValue), fs.File_ServExtra_id);
                }
                else
                {
                    SalvaRangesSerExtraVazio(Convert.ToDateTime(txtDataFromTours.Text), Convert.ToDateTime(txtDataToTours.Text), markupcliente, markupdesconto, Convert.ToInt32(ddlSuppliersServExtra.SelectedValue), fs.File_ServExtra_id);
                }

                PopulaNewQuote(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToInt32(ViewState["QuoteAtiva"]));

                MostrarMsg("Registro cadastrado com sucesso.");


                //txtNomeServExtra.Text = "";
                //PopulaDropSuppliersServExtra();
                //PopularddlTipoServExtra();

                //PopularGridListCarrinhoExtras(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                //CalculaValorTotal();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        protected void SalvaRangesSerExtraExistentes(DateTime dtFrom, DateTime dtTo, decimal markupcliente, decimal descontocliente, int IdSupplier, int IdTarifa)
        {
            try
            {

                RangeDal rd = new RangeDal();
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                CambioDAL cambDal = new CambioDAL();

                int IdQuot = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));

                int num = 0;
                bool exists2;
                List<string> BasesAdicionadas2 = new List<string>();
                List<int> RangesID = new List<int>();
                List<int> ids = new List<int>();

                foreach (Ranges rgs in rd.ListarTodos(IdQuot))
                {

                    if (!rgs.Ranges_de.Equals("TC"))
                    {
                        exists2 = BasesAdicionadas2.Exists(element => element.Equals(rgs.Ranges_de));
                        num = 1;
                    }
                    else
                    {
                        exists2 = false;
                    }

                    if (!exists2 && num == 1)
                    {
                        BasesAdicionadas2.Add(rgs.Ranges_de);

                        if (rgs.Ranges_de.Equals("TC"))
                        {
                            num = 0;
                        }

                        int[] arrayOf = ids.ToArray();

                        Ranges range = new Ranges();
                        range.Ranges_de = rgs.Ranges_de;
                        range.Ranges_ate = rgs.Ranges_ate;
                        range.Quotation_Id = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));
                        range.Flag = "extra";

                        range.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                        if (rd.ObterPorTarifaOne(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), rgs.Ranges_de, rgs.Ranges_ate) != null)
                        {
                            range.Ordem = rd.ObterPorTarifaOne(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text)), rgs.Ranges_de, rgs.Ranges_ate).Ordem;
                        }
                        else
                        {
                            range.Ordem = rd.ObterPorTarifaLast(IdTarifa).Ordem + 1;
                        }

                        if (rgs.Ranges_de.Equals("TC", StringComparison.OrdinalIgnoreCase))
                        {
                            range.RangeID = arrayOf[0];

                            int numToRemove = arrayOf[0];
                            arrayOf = arrayOf.Where(val => val != numToRemove).ToArray();
                            ids.Clear();
                        }

                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        {

                            SupplierDAL sd = new SupplierDAL();
                            MarkupPaisDAL mkd = new MarkupPaisDAL();

                            Supplier spp = sd.ObterPorId(Convert.ToInt32(ddlSuppliersServExtra.SelectedValue));
                            MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                            range.markup = mkp.MarkupServ;
                            range.desconto = mkp.Desconto;
                            range.markupNet = markupcliente;
                            range.descontoNet = descontocliente;
                        }
                        else
                        {
                            range.markup = markupcliente;
                            range.desconto = descontocliente;
                            range.markupNet = 0;
                            range.descontoNet = 0;
                        }

                        range.Valor = 0;
                        range.ValorTotal = 0;
                        range.VendaNet = 0;
                        range.Venda = 0;

                        TarifaDAL td = new TarifaDAL();

                        range.FileTabelaId = IdTarifa;

                        rd.Salvar(range);

                        if (!range.Ranges_de.Equals("TC", StringComparison.OrdinalIgnoreCase))
                        {
                            ids.Add(range.Ranges_id);
                        }

                        //AcertaRange(range.Ranges_id, IdTarifa, range.Flag);
                    }

                }

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void SalvaRangesSerExtraVazio(DateTime dtFrom, DateTime dtTo, decimal markupcliente, decimal descontocliente, int IdSupplier, int IdTarifa)
        {
            try
            {

                RangeDal rd = new RangeDal();
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                CambioDAL cambDal = new CambioDAL();

                Ranges range = new Ranges();
                range.Ranges_de = txtBaseDeNew.Text;
                range.Ranges_ate = txtBaseAteNew.Text;
                range.Quotation_Id = fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text));
                range.Flag = "extra";

                range.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                if (rd.ListarTodosGroup(fcd.RetornaQuote(fcd.RetornaFile(txtQuoteNumber.Text))).Count == 0)
                {
                    range.Ordem = 1;
                }
                else
                {
                    range.Ordem = rd.ObterPorTarifaLast(IdTarifa).Ordem + 1;
                }

                if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                {

                    SupplierDAL sd = new SupplierDAL();
                    MarkupPaisDAL mkd = new MarkupPaisDAL();

                    Supplier spp = sd.ObterPorId(Convert.ToInt32(ddlSuppliersServExtra.SelectedValue));
                    MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                    range.markup = mkp.MarkupServ;
                    range.desconto = mkp.Desconto;
                    range.markupNet = markupcliente;
                    range.descontoNet = descontocliente;
                }
                else
                {
                    range.markup = markupcliente;
                    range.desconto = descontocliente;
                    range.markupNet = 0;
                    range.descontoNet = 0;
                }

                range.Valor = 0;
                range.ValorTotal = 0;
                range.VendaNet = 0;
                range.Venda = 0;

                TarifaDAL td = new TarifaDAL();

                range.FileTabelaId = IdTarifa;

                rd.Salvar(range);

                AcertaRange(range.Ranges_id, IdTarifa, range.Flag);

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void imgAtualizaCarrinhoServExtra_Command(object sender, CommandEventArgs e)
        {
            try
            {

                FileServExtraDAL ftd = new FileServExtraDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                int IdTarifa = Convert.ToInt32(e.CommandArgument);

                foreach (GridViewRow item in GridFileCarrinhoExtras.Rows)
                {
                    TextBox txtQtdTarifas = (TextBox)item.FindControl("txtQtdTarifas");
                    Label IdFileServExtra = (Label)item.FindControl("IdFileServExtra");
                    TextBox txtMarkup = (TextBox)item.FindControl("txtMarkup");
                    TextBox txtMarkupNet = (TextBox)item.FindControl("txtMarkupNet");
                    TextBox txtDesconto = (TextBox)item.FindControl("txtDesconto");
                    TextBox txtDescontoNet = (TextBox)item.FindControl("txtDescontoNet");
                    TextBox txtValorTarifas = (TextBox)item.FindControl("txtValorTarifas");

                    if (IdTarifa == Convert.ToInt32(IdFileServExtra.Text))
                    {
                        File_ServExtra ft = new File_ServExtra();

                        ft.File_ServExtra_valor = Convert.ToDecimal(txtValorTarifas.Text);
                        ft.markup = Convert.ToDecimal(txtMarkup.Text);
                        ft.markupNet = Convert.ToDecimal(txtMarkupNet.Text);
                        ft.desconto = Convert.ToDecimal(txtDesconto.Text);
                        ft.descontoNet = Convert.ToDecimal(txtDescontoNet.Text);
                        ft.Qtd_ServExtr = Convert.ToInt32(txtQtdTarifas.Text);
                        ft.File_ServExtra_id = IdTarifa;
                        ft.UpdVenda = false;

                        ftd.Atualizar(ft);
                    }

                }


                PopularGridListCarrinhoExtras(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                CalculaValorTotal();
                MostrarMsg("File atualizado com sucesso.");

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void ExluirFileCarrinhoExtra(object sender, CommandEventArgs e)
        {
            try
            {

                int myid = Convert.ToInt32(e.CommandArgument);

                FileServExtraDAL ftd = new FileServExtraDAL();

                File_ServExtra ft = ftd.ObterPorId(myid);

                ftd.Excluir(ft);


                MostrarMsg("Registro excluído com sucesso.");
                PopularGridListCarrinhoExtras(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                CalculaValorTotal();
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void imgAtualizaCarrinhoServExtraVenda_Command(object sender, CommandEventArgs e)
        {
            try
            {
                FileServExtraDAL ftd = new FileServExtraDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                int IdTarifa = Convert.ToInt32(e.CommandArgument);

                foreach (GridViewRow item in GridFileCarrinhoExtras.Rows)
                {
                    TextBox txtQtdTarifas = (TextBox)item.FindControl("txtQtdTarifas");
                    Label IdFileServExtra = (Label)item.FindControl("IdFileServExtra");
                    TextBox txtValorTarifas = (TextBox)item.FindControl("txtValorTarifas");
                    TextBox txtVenda = (TextBox)item.FindControl("txtVenda");
                    TextBox txtVendaNet = (TextBox)item.FindControl("txtVendaNet");


                    if (IdTarifa == Convert.ToInt32(IdFileServExtra.Text))
                    {

                        File_ServExtra ft = new File_ServExtra();

                        double mult = Convert.ToDouble(txtVenda.Text) * Convert.ToDouble(txtQtdTarifas.Text);
                        double mkpNew = ((Convert.ToDouble(txtVenda.Text) / Convert.ToDouble(txtValorTarifas.Text)) * 100) - 100;

                        double vlNew = (Convert.ToDouble(txtVendaNet.Text) * mkpNew) / 100;

                        ft.S_merc_tarif_vendaNet = Convert.ToDecimal(vlNew) + Convert.ToDecimal(txtValorTarifas.Text);
                        ft.markup = Convert.ToDecimal(mkpNew);
                        ft.File_ServExtra_venda = Convert.ToDecimal(txtVenda.Text);
                        ft.File_ServExtra_total = Convert.ToDecimal(mult);
                        ft.File_ServExtra_id = IdTarifa;

                        ftd.AtualizarVenda(ft);
                    }

                }


                PopularGridListCarrinhoExtras(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                MostrarMsg("File atualizado com sucesso.");
                CalculaValorTotal();

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        #endregion

        #region Regras Reports

        protected void ddlTipoRpt_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlTipoRpt.SelectedItem.Value != "5")
                ddlPais.Visible = false;

            switch (ddlTipoRpt.SelectedValue)
            {
                case "1":
                    //EmitirRelatorioServiceConfirmation();
                    break;
                case "2":

                    InvoiceDAL iDAL = new InvoiceDAL();

                    FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                    QuotationGrupoDAL qgd = new QuotationGrupoDAL();

                    File_Carrinho fc = fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                    Quotation_Grupo qg = qgd.ObterPorId(fc.Quotation_Grupo_Id);


                    gridHistoricoInvoice.DataSource = iDAL.listaInvoicesPorQuotationGrupo(Convert.ToInt32(qg.Quotation_Id));
                    gridHistoricoInvoice.DataBind();


                    //EmitirRelatorioInvoice();
                    break;
                case "3":
                    //EmitirRelatorioVoucher();
                    break;
                case "5":
                    DataTable dt = new DataTable();
                    dt.Columns.Add("PaisID");
                    dt.Columns.Add("PaisNome");

                    foreach (GridViewRow item in GridFileCarrinhoHoteis.Rows)
                    {
                        Label lblNomeCidade = (Label)item.FindControl("lblCidade");
                        Cidade cid = new CidadeDAL().ObterPorNome(lblNomeCidade.Text);
                        Pai pais = new PaisDAL().ObterPorId(Convert.ToInt32(cid.PAIS_id));

                        bool hasCountry = false;

                        foreach (DataRow dr in dt.Rows)
                        {
                            if (dr["PaisID"].ToString() == pais.PAIS_id.ToString())
                                hasCountry = true;
                        }

                        if (!hasCountry)
                            dt.Rows.Add(pais.PAIS_id, pais.PAIS_nome);
                    }

                    ddlPais.DataSource = dt;
                    ddlPais.DataValueField = "PaisID";
                    ddlPais.DataTextField = "PaisNome";
                    ddlPais.DataBind();
                    ddlPais.Items.Add(new ListItem() { Value = "0", Text = "All Countries" });
                    ddlPais.Visible = true;
                    break;
            }


        }

        protected void EmitirRelatorio(object sender, EventArgs e)
        {
            try
            {

                switch (ddlTipoRpt.SelectedValue)
                {
                    case "1":
                        EmitirRelatorioServiceConfirmation();
                        break;
                    case "2":
                        EmitirRelatorioInvoice();
                        break;
                    case "3":
                        EmitirRelatorioVoucher();
                        break;
                    case "4":
                        EmitirRelatorioMapaServicos();
                        break;
                    case "5":
                        EmitirRelatorioFilePrint();
                        break;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }

        }

        protected void EmitirRelatorioFilePrint()
        {
            QuoteTarifasDAL ftd = new QuoteTarifasDAL();
            QuoteTransDAL fttd = new QuoteTransDAL();
            QuoteServExtDAL fsed = new QuoteServExtDAL();

            Quote_ServExtra fse = new Quote_ServExtra();
            Quote_Transf ftt = new Quote_Transf();
            Quote_Tarifas ft = new Quote_Tarifas();

            FileCarrinhoDAL fcd = new FileCarrinhoDAL();

            DSFilePrint dsFilePrint = new DSFilePrint();
            DataTable dt = dsFilePrint.Tables["FilePrint"];

            double totalValorHotel = 0;
            double totalValorHotelVenda = 0;
            double totalValorHotelMarkup = 0;
            double totalValorHotelNetNet = 0;

            double totalValorServicos = 0;
            double totalValorServicosVenda = 0;
            double totalValorServicosMarkup = 0;
            double totalValorServicosNetNet = 0;

            double totalValorExtra = 0;
            double totalValorExtraVenda = 0;
            double totalValorExtraMarkup = 0;
            double totalValorExtraNetNet = 0;

            CidadeDAL cDAL = new CidadeDAL();
            PaisDAL pDAL = new PaisDAL();

            int idFile = fcd.RetornaFileID(Convert.ToInt32(ViewState["IdQuotGrupo"]));

            foreach (GridViewRow item in GridBasesTarifasNewFile.Rows)
            {
                Label lblFlag = (Label)item.FindControl("lblFlag");

                #region Hotel
                if (lblFlag.Text == "hotel")
                {
                    Label lblCidade = (Label)item.FindControl("lblCidade");
                    Cidade cid = cDAL.ObterPorNome(lblCidade.Text);
                    Pai pais = pDAL.ObterPorId(Convert.ToInt32(cid.PAIS_id));

                    if (ddlPais.SelectedItem.Value != "0")
                        if (pais.PAIS_id != Convert.ToInt32(ddlPais.SelectedItem.Value))
                            continue;

                    Label lblIdRetorna = (Label)item.FindControl("lblIdRetorna");

                    Quote_Tarifas qt = ftd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                    //Quote_Transf
                    //Quote_ServExtra

                    Label lblNomeSupplier = (Label)item.FindControl("lblNomeSupplier");
                    Label lblCategoria = (Label)item.FindControl("lblCategoria");
                    Label lblRoom = (Label)item.FindControl("lblRoom");
                    Label lblDataFrom = (Label)item.FindControl("lblFrom");
                    Label lblDataTo = (Label)item.FindControl("lblTo");
                    Label lblFileTarifaID = (Label)item.FindControl("IdFileTarifas");

                    string PayingPax = "", SupplierPayingPax = "", Paxs = "";

                    if (ftd.ObterPorId(Convert.ToInt32(lblFileTarifaID.Text)).Paying_Pax != null)
                    {
                        ft = ftd.ObterPorId(Convert.ToInt32(lblFileTarifaID.Text));
                        PayingPax = ft.Paying_Pax.ToString();
                        SupplierPayingPax = ft.Supp_Paying_Pax.ToString();
                        Paxs = ft.Paxs.ToString();
                    }

                    double multvenda;

                    if (qt.S_merc_tarif_venda.Equals("") || qt.S_merc_tarif_vendaNet.Equals(""))
                        multvenda = 0;
                    else
                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                            multvenda = Convert.ToDouble(qt.S_merc_tarif_venda) * Convert.ToDouble(qt.Qtd_Tarifas);
                        else
                            multvenda = Convert.ToDouble(qt.S_merc_tarif_venda) * Convert.ToDouble(qt.Qtd_Tarifas);

                    double mult;

                    if (qt.S_merc_tarif_venda.Equals("") || qt.S_merc_tarif_vendaNet.Equals(""))
                        mult = 0;
                    else
                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                            mult = Convert.ToDouble(qt.S_merc_tarif_vendaNet) * Convert.ToDouble(qt.Qtd_Tarifas);
                        else
                            mult = Convert.ToDouble(qt.S_merc_tarif_valor) * Convert.ToDouble(qt.Qtd_Tarifas) * Convert.ToInt32(qt.NumNoites.ToString());




                    totalValorHotel = totalValorHotel + mult;
                    totalValorHotelVenda = totalValorHotelVenda + multvenda;
                    totalValorHotelNetNet += Convert.ToDouble(qt.S_merc_tarif_valor);

                    DataRow dr = dt.NewRow();


                    dr["supplierNome"] = lblNomeSupplier.Text;
                    dr["roomType"] = lblCategoria.Text + " - " + lblRoom.Text;
                    dr["dateIn"] = lblDataFrom.Text;
                    dr["dateOut"] = lblDataTo.Text;
                    dr["numberNights"] = qt.NumNoites.ToString();
                    dr["package"] = qt.NumNoites.ToString();
                    dr["city"] = cid.CID_nome;
                    dr["payingPax"] = PayingPax;
                    dr["netNet"] = qt.S_merc_tarif_valor.ToString();
                    dr["markupPais"] = qt.markup.ToString();
                    dr["descPais"] = qt.desconto;
                    dr["net"] = qt.S_merc_tarif_vendaNet.ToString();
                    dr["markupCliente"] = qt.markupNet.ToString();
                    dr["descCliente"] = qt.descontoNet;
                    dr["venda"] = qt.S_merc_tarif_venda.ToString();
                    dr["total"] = qt.S_merc_tarif_valor.ToString();
                    dr["pax"] = Paxs;
                    dr["supplierPayingPax"] = SupplierPayingPax;

                    dt.Rows.Add(dr);
                }
                #endregion

                #region Serviço
                else if (lblFlag.Text == "servico")
                {
                    Label lblIdRetorna = (Label)item.FindControl("lblIdRetorna");
                    Quote_Transf qt = fttd.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                    var s = new SupplierDAL().ObterPorId(Convert.ToInt32(qt.S_id));

                    Label lblNomeCidade = (Label)item.FindControl("lblCidade");
                    Cidade cid = cDAL.ObterPorId((int)s.CID_id);
                    Pai pais = pDAL.ObterPorId(Convert.ToInt32(cid.PAIS_id));

                    if (ddlPais.SelectedItem.Value != "0")
                        if (pais.PAIS_id != Convert.ToInt32(ddlPais.SelectedItem.Value))
                            continue;

                    Label lblNomeSupplier = (Label)item.FindControl("lblNomeSupplier");
                    //Label lblNomeTrf = (Label)item.FindControl("lblNomeTrf");
                    Label lblDataFrom = (Label)item.FindControl("lblFrom");
                    Label lblDataTo = (Label)item.FindControl("lblTo");
                    Label lblFileTransfID = (Label)item.FindControl("IdFileTarifas");

                    string PayingPax = "", SupplierPayingPax = "", Paxs = "";

                    if (fttd.ObterPorId(Convert.ToInt32(lblFileTransfID.Text)).Paying_Pax != null)
                    {
                        ftt = fttd.ObterPorId(Convert.ToInt32(lblFileTransfID.Text));
                        PayingPax = ftt.Paying_Pax.ToString();
                        SupplierPayingPax = ftt.Supp_Paying_Pax.ToString();
                        Paxs = ftt.Paxs.ToString();
                    }


                    double multvenda;

                    if (qt.Transf_venda.Equals("") || qt.Transf_vendaNet.Equals(""))
                        multvenda = 0;




                    else
                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                            multvenda = Convert.ToDouble(qt.Transf_venda) * Convert.ToDouble(qt.Qtd_Transf);
                        else
                            multvenda = Convert.ToDouble(qt.Transf_venda) * Convert.ToDouble(qt.Qtd_Transf);
                    //multvenda = Convert.ToDouble(txtVendaNet.Text) * Convert.ToDouble(txtQtdTarifas.Text);

                    double mult;

                    if (qt.Transf_venda.Equals("") || qt.Transf_vendaNet.Equals(""))
                        mult = 0;




                    else
                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                            mult = Convert.ToDouble(qt.Transf_vendaNet) * Convert.ToDouble(qt.Qtd_Transf);
                        else
                            mult = Convert.ToDouble(qt.Transf_valor) * Convert.ToDouble(qt.Qtd_Transf);

                    totalValorServicos += mult;
                    totalValorServicosVenda += multvenda;
                    totalValorServicosNetNet += Convert.ToDouble(qt.Transf_valor);

                    DataRow dr = dt.NewRow();

                    dr["supplierNome"] = lblNomeSupplier.Text;
                    dr["roomType"] = qt.Trf_Tours;
                    dr["dateIn"] = lblDataFrom.Text;
                    dr["dateOut"] = lblDataTo.Text;
                    dr["numberNights"] = "";
                    dr["package"] = "";
                    dr["city"] = cid.CID_nome;
                    dr["payingPax"] = PayingPax;
                    dr["netNet"] = qt.Transf_valor.ToString();
                    dr["markupPais"] = qt.markup.ToString();
                    dr["descPais"] = qt.desconto.ToString();
                    dr["net"] = qt.Transf_vendaNet;
                    dr["markupCliente"] = qt.markupNet.ToString();
                    dr["descCliente"] = qt.descontoNet.ToString();
                    dr["venda"] = qt.Transf_venda.ToString();
                    dr["total"] = qt.Transf_total.ToString();
                    dr["pax"] = Paxs;
                    dr["supplierPayingPax"] = SupplierPayingPax;

                    dt.Rows.Add(dr);
                }
                #endregion

                #region Serv_Extra
                else if (lblFlag.Text == "extra")
                {
                    Label lblIdRetorna = (Label)item.FindControl("lblIdRetorna");
                    Quote_ServExtra qse = fsed.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));

                    Label lblNomeCidade = (Label)item.FindControl("lblCidade");
                    Cidade cid = cDAL.ObterPorNome(lblNomeCidade.Text);
                    Pai pais = pDAL.ObterPorId(Convert.ToInt32(cid.PAIS_id));

                    if (ddlPais.SelectedItem.Value != "0")
                        if (pais.PAIS_id != Convert.ToInt32(ddlPais.SelectedItem.Value))
                            continue;

                    Label lblNomeSupplier = (Label)item.FindControl("lblNomeSupplier");
                    //Label lblNomeServExtra = (Label)item.FindControl("lblNomeServExtra");
                    Label lblDataFrom = (Label)item.FindControl("lblFrom");
                    Label lblDataTo = (Label)item.FindControl("lblTo");
                    Label lblFileTransfID = (Label)item.FindControl("IdFileTarifas");

                    string PayingPax = "", SupplierPayingPax = "", Paxs = "";

                    if (fttd.ObterPorId(Convert.ToInt32(lblFileTransfID.Text)).Paying_Pax != null)
                    {
                        ftt = fttd.ObterPorId(Convert.ToInt32(lblFileTransfID.Text));
                        PayingPax = ftt.Paying_Pax.ToString();
                        SupplierPayingPax = ftt.Supp_Paying_Pax.ToString();
                        Paxs = ftt.Paxs.ToString();
                    }


                    if (!(qse.File_ServExtra_valor.Equals("") && qse.File_ServExtra_venda.Equals("") && qse.Qtd_ServExtr.Equals("")))
                    {
                        double multvenda;

                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                            multvenda = Convert.ToDouble(qse.File_ServExtra_venda) * Convert.ToDouble(qse.Qtd_ServExtr);
                        else
                            multvenda = Convert.ToDouble(qse.File_ServExtra_venda) * Convert.ToDouble(qse.Qtd_ServExtr);

                        double mult;

                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                            mult = Convert.ToDouble(qse.File_ServExtra_vendaNet) * Convert.ToDouble(qse.Qtd_ServExtr);
                        else
                            mult = Convert.ToDouble(qse.File_ServExtra_valor) * Convert.ToDouble(qse.Qtd_ServExtr);


                        totalValorExtra += mult;
                        totalValorExtraVenda += multvenda;
                        totalValorExtraNetNet += Convert.ToDouble(qse.File_ServExtra_valor);
                    }




                    DataRow dr = dt.NewRow();

                    dr["supplierNome"] = lblNomeSupplier.Text;
                    dr["roomType"] = qse.File_ServExtra_nome;

                    dr["dateIn"] = lblDataFrom.Text;
                    dr["dateOut"] = lblDataTo.Text;
                    dr["numberNights"] = "";
                    dr["package"] = "";
                    dr["city"] = cid.CID_nome;
                    dr["payingPax"] = PayingPax;
                    dr["netNet"] = qse.File_ServExtra_valor;
                    dr["markupPais"] = qse.markup.ToString();


                    dr["descPais"] = qse.desconto;
                    dr["net"] = qse.File_ServExtra_vendaNet;

                    dr["markupCliente"] = qse.markupNet;
                    dr["descCliente"] = qse.descontoNet;
                    dr["venda"] = qse.File_ServExtra_venda;
                    dr["total"] = qse.File_ServExtra_total;


                    dr["pax"] = Paxs;
                    dr["supplierPayingPax"] = SupplierPayingPax;

                    dt.Rows.Add(dr);
                }
                #endregion

            }           

            if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                totalValorHotelMarkup = ((totalValorHotelVenda - totalValorHotel) / totalValorHotel) * 100;
            else
                totalValorHotelMarkup = ((totalValorHotelVenda - totalValorHotel) * 100) / totalValorHotelVenda;

            if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                totalValorServicosMarkup = (((totalValorServicosVenda + totalValorExtraVenda) - (totalValorServicos + totalValorExtra)) / (totalValorServicos + totalValorExtra)) * 100;
            else
                totalValorServicosMarkup = (((totalValorServicosVenda + totalValorExtraVenda) - (totalValorServicos + totalValorExtra)) * 100) / (totalValorServicosVenda + totalValorExtraVenda);

            totalValorExtraMarkup = ((totalValorExtraVenda - totalValorExtra) * 100) / totalValorExtraVenda;

            lblValorTotalHotelCarrinho.Text = totalValorHotel.ToString("N");
            lblValorTotalHotelCarrinhoVenda.Text = totalValorHotelVenda.ToString("N");
            lblValorTotalHotelMarkup.Text = totalValorHotelMarkup.ToString("N");

            lblValorTotalServicosCarrinho.Text = (totalValorServicos + totalValorExtra).ToString("N");
            lblValorTotalServicosCarrinhoVenda.Text = (totalValorServicosVenda + totalValorExtraVenda).ToString("N");
            lblValorTotalServicosCarrinhoMarkup.Text = totalValorServicosMarkup.ToString("N");

            lblValorGrandTotalCarrinho.Text = (totalValorHotel + totalValorServicos + totalValorExtra).ToString("N");
            lblValorGrandTotalCarrinhoVenda.Text = (totalValorHotelVenda + totalValorServicosVenda + totalValorExtraVenda).ToString("N");

            if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                lblValorGrandTotalCarrinhoMarkup.Text = (((Convert.ToDouble(lblValorGrandTotalCarrinhoVenda.Text) - Convert.ToDouble(lblValorGrandTotalCarrinho.Text)) / Convert.ToDouble(lblValorGrandTotalCarrinho.Text)) * 100).ToString("N");
            else
                lblValorGrandTotalCarrinhoMarkup.Text = (((Convert.ToDouble(lblValorGrandTotalCarrinhoVenda.Text) - Convert.ToDouble(lblValorGrandTotalCarrinho.Text)) * 100) / Convert.ToDouble(lblValorGrandTotalCarrinhoVenda.Text)).ToString("N");

            //Popular o Relatorio com os dados obtidos pela DataTable
            RptFilePrint rpt = new RptFilePrint();

            CrystalDecisions.CrystalReports.Engine.TextObject objTotalHotel = rpt.ReportDefinition.Sections[1].ReportObjects["txtValorHotel"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject objTotalHotelTotal = rpt.ReportDefinition.Sections[1].ReportObjects["txtValorHotelVenda"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject objTotalHotelPercentual = rpt.ReportDefinition.Sections[1].ReportObjects["totalValorHotelMarkup"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject objTotalHotelNetNet = rpt.ReportDefinition.Sections[1].ReportObjects["totalValorHotelNetNet"] as TextObject;

            CrystalDecisions.CrystalReports.Engine.TextObject objTotalServices = rpt.ReportDefinition.Sections[1].ReportObjects["totalValorExtra"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject objTotalServicesTotal = rpt.ReportDefinition.Sections[1].ReportObjects["totalValorExtraVenda"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject objTotalServicesPercentual = rpt.ReportDefinition.Sections[1].ReportObjects["totalValorExtraMarkup"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject objTotalServicesNetNet = rpt.ReportDefinition.Sections[1].ReportObjects["totalValorServicosNetNet"] as TextObject;

            CrystalDecisions.CrystalReports.Engine.TextObject objGrandTotal = rpt.ReportDefinition.Sections[1].ReportObjects["totalValorServicos"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject objGranTotalTotal = rpt.ReportDefinition.Sections[1].ReportObjects["totalValorServicosVenda"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject objGranTotalPercentual = rpt.ReportDefinition.Sections[1].ReportObjects["totalValorServicosMarkup"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject objGranTotalNetNet = rpt.ReportDefinition.Sections[1].ReportObjects["totalValorExtraNetNet"] as TextObject;

            CrystalDecisions.CrystalReports.Engine.TextObject objPais = rpt.ReportDefinition.Sections[1].ReportObjects["txtPais"] as TextObject;

            objTotalHotel.Text = totalValorHotel.ToString("n");
            objTotalHotelTotal.Text = totalValorHotelVenda.ToString("n");
            objTotalHotelPercentual.Text = totalValorHotelMarkup.ToString("n") + "%";

            objTotalServices.Text = (totalValorServicos + totalValorExtra).ToString("N"); //totalValorExtra.ToString("n");
            objTotalServicesTotal.Text = (totalValorServicosVenda + totalValorExtraVenda).ToString("N"); //totalValorExtraVenda.ToString("n");
            objTotalServicesPercentual.Text = totalValorServicosMarkup.ToString("N") + "%"; //totalValorExtraMarkup.ToString("n") + "%";

            objGrandTotal.Text = (totalValorHotel + totalValorServicos + totalValorExtra).ToString("n");
            objGranTotalTotal.Text = (totalValorHotelVenda + totalValorServicosVenda + totalValorExtraVenda).ToString("n");
            objGranTotalPercentual.Text = ((totalValorHotelMarkup + totalValorServicosMarkup) / 2).ToString("n") + "%";

            //Usuario u = Session[Convert.ToString(Session["emailLogado"])] as Usuario;
            Usuario u = ReadCookiesUser();

            if (u != null)
                if (u.Cliente_id == null)
                {
                    objTotalHotelNetNet.Text = totalValorHotelNetNet.ToString("n");
                    objTotalServicesNetNet.Text = (totalValorServicosNetNet + totalValorExtraNetNet).ToString("n");
                    objGranTotalNetNet.Text = (totalValorHotelNetNet + totalValorServicosNetNet + totalValorExtraNetNet).ToString("n");
                }

            objPais.Text = ddlPais.SelectedItem.Text;

            rpt.SetDataSource(dt);

            switch (ddlFormato.SelectedValue)
            {
                case "1":

                    rpt.ExportToHttpResponse(
                        ExportFormatType.PortableDocFormat,
                        Response, true, "service");
                    break;

                case "2":
                    rpt.ExportToHttpResponse(
                        ExportFormatType.WordForWindows,
                        Response, true, "service");
                    break;

                case "3":
                    rpt.ExportToHttpResponse(
                        ExportFormatType.Excel,
                        Response, true, "service");
                    break;
            }
        }

        protected void EmitirRelatorioServiceConfirmation()
        {
            try
            {

                string NomeEmpresa = ConfigurationManager.AppSettings["NomeEmpresa"];
                string EnderecoEmpresa = ConfigurationManager.AppSettings["EnderecoEmpresa"];
                string ContatoEmpresa = ConfigurationManager.AppSettings["ContatoEmpresa"];

                ClienteDAL clid = new ClienteDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();
                MoedaDAL moed = new MoedaDAL();

                File_Carrinho fc = fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                Quotation_Grupo qg = qgd.ObterPorId(fc.Quotation_Grupo_Id);
                DAL.Entity.Cliente cl = clid.ObterPorId(qg.Cliente_id);

                int IdFileCarrinho = fc.File_id;
                //string moeda = fc.File_Tarifas.First().Moeda;
                string moeda = moed.ObterPorId(Convert.ToInt32(qg.Moeda_id)).Moeda_sigla;

                //Instanciando o DataSet
                DSQuote ds = new DSQuote();

                DataTable dt = ds.Tables["QUOTE"];

                //Acessar a camada de persistência
                //FileTarifasDAL d = new FileTarifasDAL();
                QuoteTarifasDAL d = new QuoteTarifasDAL();

                foreach (Quote_Tarifas p in d.ListarTodos(IdFileCarrinho))
                {
                    //Criar um novo registro dentro da DataTable
                    DataRow dr = dt.NewRow();

                    dr["DESCRICAO"] = p.S_nome + "     " + p.Categoria + " - " + p.Room + "   Paxs " + p.Paying_Pax + "x";
                    dr["VENDA"] = p.S_merc_tarif_venda;
                    dr["TOTAL"] = p.S_merc_tarif_total;

                    //Gravo o registro
                    dt.Rows.Add(dr);
                }

                //FileTransfersDAL ftd = new FileTransfersDAL();
                QuoteTransDAL qtd = new QuoteTransDAL();

                foreach (Quote_Transf p in qtd.ListarTodos(IdFileCarrinho))
                {
                    DataRow dr = dt.NewRow();

                    dr["DESCRICAO"] = p.Transf_nome + "   Paxs " + p.Paying_Pax + "x";
                    dr["VENDA"] = p.Transf_venda;
                    dr["TOTAL"] = p.Transf_total;

                    //Gravo o registro
                    dt.Rows.Add(dr);
                }

                //FileServExtraDAL fse = new FileServExtraDAL();
                QuoteServExtDAL qse = new QuoteServExtDAL();

                foreach (Quote_ServExtra fser in qse.ListarTodos(IdFileCarrinho))
                {
                    DataRow dr = dt.NewRow();

                    dr["DESCRICAO"] = fser.File_ServExtra_nome + "   Paxs " + fser.Paying_Pax + "x";
                    dr["VENDA"] = fser.File_ServExtra_venda;
                    dr["TOTAL"] = fser.File_ServExtra_total;

                    //Gravo o registro
                    dt.Rows.Add(dr);
                }

                //Popular o Relatorio com os dados obtidos pela DataTable
                RptQuote rpt = new RptQuote();

                CrystalDecisions.CrystalReports.Engine.TextObject ObjTitulo = rpt.ReportDefinition.Sections[1].ReportObjects["txtTitulo"] as TextObject;
                ObjTitulo.Text = "SERVICES CONFIRMATION";

                CrystalDecisions.CrystalReports.Engine.TextObject ObjNomeEmpresa = rpt.ReportDefinition.Sections[1].ReportObjects["NomeEmpresa"] as TextObject;
                CrystalDecisions.CrystalReports.Engine.TextObject ObjEnderecoEmpresa = rpt.ReportDefinition.Sections[1].ReportObjects["EnderecoEmpresa"] as TextObject;
                CrystalDecisions.CrystalReports.Engine.TextObject ObjContatoEmpresa = rpt.ReportDefinition.Sections[1].ReportObjects["ContatoEmpresa"] as TextObject;
                CrystalDecisions.CrystalReports.Engine.TextObject ObjMoeda = rpt.ReportDefinition.Sections[1].ReportObjects["Moeda"] as TextObject;
                ObjNomeEmpresa.Text = NomeEmpresa;
                ObjEnderecoEmpresa.Text = EnderecoEmpresa;
                ObjContatoEmpresa.Text = ContatoEmpresa;
                ObjMoeda.Text = moeda;

                CrystalDecisions.CrystalReports.Engine.TextObject ObjToCliente = rpt.ReportDefinition.Sections[1].ReportObjects["txtTo"] as TextObject;
                CrystalDecisions.CrystalReports.Engine.TextObject ObjGrupoNome = rpt.ReportDefinition.Sections[1].ReportObjects["txtPaxGrp"] as TextObject;
                CrystalDecisions.CrystalReports.Engine.TextObject ObjFileNumber = rpt.ReportDefinition.Sections[1].ReportObjects["txtFile"] as TextObject;
                CrystalDecisions.CrystalReports.Engine.TextObject ObjQuotNumber = rpt.ReportDefinition.Sections[1].ReportObjects["txtGrpId"] as TextObject;
                ObjToCliente.Text = cl.Cliente_nome;
                ObjGrupoNome.Text = qg.Pax_Group_Name;
                ObjFileNumber.Text = qg.Quotation_Id.ToString();
                ObjQuotNumber.Text = qg.Quotation_Grupo_Id.ToString();

                rpt.SetDataSource(dt);

                switch (ddlFormato.SelectedValue)
                {
                    case "1":

                        //PdfWriter.GetInstance(pdfDoc, new FileStream(context.Server.MapPath("~") + "/PDF/" + reportName + ".pdf", FileMode.Create));

                        rpt.ExportToHttpResponse(
                            ExportFormatType.PortableDocFormat,
                            Response, true, "service");
                        break;

                    case "2":
                        rpt.ExportToHttpResponse(
                            ExportFormatType.WordForWindows,
                            Response, true, "service");
                        break;

                    case "3":
                        rpt.ExportToHttpResponse(
                            ExportFormatType.Excel,
                            Response, true, "service");
                        break;
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        protected void EmitirRelatorioInvoice()
        {
            try
            {

                string NomeEmpresa = ConfigurationManager.AppSettings["NomeEmpresa"];
                string EnderecoEmpresa = ConfigurationManager.AppSettings["EnderecoEmpresa"];
                string ContatoEmpresa = ConfigurationManager.AppSettings["ContatoEmpresa"];


                decimal grandTotal = 0;

                InvoiceDAL id = new InvoiceDAL();
                ClienteDAL clid = new ClienteDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();
                MoedaDAL moed = new MoedaDAL();

                File_Carrinho fc = fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                Quotation_Grupo qg = qgd.ObterPorId(fc.Quotation_Grupo_Id);
                DAL.Entity.Cliente cl = clid.ObterPorId(qg.Cliente_id);

                int IdFileCarrinho = fc.File_id;
                string moeda = moed.ObterPorId(Convert.ToInt32(qg.Moeda_id)).Moeda_sigla;




                Invoice inv = new Invoice();
                inv.Quotation_Grupo_Id = fc.Quotation_Grupo_Id;

                string path = Server.MapPath("~/Invoices/");

                string nomeGuid = Guid.NewGuid().ToString() + ".pdf";

                string fileName = path + nomeGuid; //Guid.NewGuid().ToString() + ".pdf";

                string caminhoFile = "/Invoices/" + nomeGuid;

                //Popular o Relatorio com os dados obtidos pela DataTable
                RptInvoice rpt = new RptInvoice();

                inv.NomeTo = cl.Cliente_nome;
                inv.Pax_Group_Name = qg.Pax_Group_Name;
                inv.Numero_File = Convert.ToInt32(qg.Quotation_Id);
                inv.DataEmissao = DateTime.Now;
                inv.Currency = moeda;
                inv.CaminhoPDF = caminhoFile;



                CrystalDecisions.CrystalReports.Engine.TextObject ObjNomeEmpresa = rpt.ReportDefinition.Sections[1].ReportObjects["NomeEmpresa"] as TextObject;
                CrystalDecisions.CrystalReports.Engine.TextObject ObjEnderecoEmpresa = rpt.ReportDefinition.Sections[1].ReportObjects["EnderecoEmpresa"] as TextObject;
                CrystalDecisions.CrystalReports.Engine.TextObject ObjContatoEmpresa = rpt.ReportDefinition.Sections[1].ReportObjects["ContatoEmpresa"] as TextObject;
                CrystalDecisions.CrystalReports.Engine.TextObject ObjMoeda = rpt.ReportDefinition.Sections[2].ReportObjects["Moeda"] as TextObject;
                ObjNomeEmpresa.Text = NomeEmpresa;
                ObjEnderecoEmpresa.Text = EnderecoEmpresa;
                ObjContatoEmpresa.Text = ContatoEmpresa;
                ObjMoeda.Text = moeda;

                CrystalDecisions.CrystalReports.Engine.TextObject ObjToCliente = rpt.ReportDefinition.Sections[1].ReportObjects["txtTo"] as TextObject;
                CrystalDecisions.CrystalReports.Engine.TextObject ObjGrupoNome = rpt.ReportDefinition.Sections[1].ReportObjects["txtPaxGrp"] as TextObject;
                CrystalDecisions.CrystalReports.Engine.TextObject ObjFileNumber = rpt.ReportDefinition.Sections[1].ReportObjects["txtFile"] as TextObject;
                CrystalDecisions.CrystalReports.Engine.TextObject ObjQuotNumber = rpt.ReportDefinition.Sections[1].ReportObjects["txtGrpId"] as TextObject;
                ObjToCliente.Text = cl.Cliente_nome;
                ObjGrupoNome.Text = qg.Pax_Group_Name;
                ObjFileNumber.Text = qg.Quotation_Id.ToString();
                ObjQuotNumber.Text = qg.Quotation_Grupo_Id.ToString();

                //Instanciando o DataSet
                DSInvoice ds = new DSInvoice();

                DataTable dt = ds.Tables["INVOICE"];

                //Acessar a camada de persistência
                //FileTarifasDAL d = new FileTarifasDAL();
                QuoteTarifasDAL d = new QuoteTarifasDAL();
                foreach (Quote_Tarifas p in d.ListarTodos(IdFileCarrinho))
                {
                    //Criar um novo registro dentro da DataTable
                    DataRow dr = dt.NewRow();

                    dr["DESCRICAO"] = p.S_nome + "     " + p.Categoria + " - " + p.Room; //+ "   Paxs " + p.Paying_Pax + "Qty";
                    dr["FROM"] = Convert.ToDateTime(p.Data_From);
                    dr["TO"] = Convert.ToDateTime(p.Data_To);
                    dr["VENDA"] = p.S_merc_tarif_venda;
                    dr["PPAX"] = p.Paying_Pax + " PERS";
                    dr["TOTAL"] = p.S_merc_tarif_total;

                    grandTotal = Convert.ToDecimal(grandTotal) + Convert.ToDecimal(p.S_merc_tarif_total);

                    //Gravo o registro
                    dt.Rows.Add(dr);
                }

                //FileTransfersDAL ftd = new FileTransfersDAL();
                QuoteTransDAL qtd = new QuoteTransDAL();
                foreach (Quote_Transf p in qtd.ListarTodos(IdFileCarrinho))
                {
                    DataRow dr = dt.NewRow();

                    dr["DESCRICAO"] = p.Transf_nome;// +"   Paxs " + p.Paying_Pax + "Qty";
                    dr["FROM"] = p.Data_From;
                    dr["TO"] = p.Data_To;
                    dr["VENDA"] = p.Transf_venda;
                    dr["PPAX"] = p.Paying_Pax + " PERS";
                    dr["TOTAL"] = p.Transf_total;

                    grandTotal = Convert.ToDecimal(grandTotal) + Convert.ToDecimal(p.Transf_total);
                    //Gravo o registro
                    dt.Rows.Add(dr);
                }

                //FileServExtraDAL fse = new FileServExtraDAL();
                QuoteServExtDAL qse = new QuoteServExtDAL();
                foreach (Quote_ServExtra fser in qse.ListarTodos(IdFileCarrinho))
                {
                    DataRow dr = dt.NewRow();

                    dr["DESCRICAO"] = fser.File_ServExtra_nome;// +"   Paxs " + fser.Paying_Pax + "Qty";
                    dr["FROM"] = fser.Data_From;
                    dr["TO"] = fser.Data_To;
                    dr["VENDA"] = fser.File_ServExtra_venda;
                    dr["PPAX"] = fser.Paying_Pax + " PERS";
                    dr["TOTAL"] = fser.File_ServExtra_total;

                    grandTotal = Convert.ToDecimal(grandTotal) + Convert.ToDecimal(fser.File_ServExtra_total);
                    //Gravo o registro
                    dt.Rows.Add(dr);
                }

                DataRow dr1 = dt.NewRow();
                //dr["INVOICE_ANTERIOR"] = "Total deste File: " + Convert.ToString(i.Invoice_id);
                dr1["TOTAL_ATUAL"] = "Total deste File: " + grandTotal;

                dt.Rows.Add(dr1);


                foreach (Invoice i in id.listaInvoicesPorQuotationGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])))
                {
                    DataRow dr = dt.NewRow();
                    dr["INVOICE_ANTERIOR"] = "Numero Inv: " + Convert.ToString(i.Invoice_id);
                    dr["TOTAL_ANTERIOR"] = "Total: " + Convert.ToString(i.Grand_Total);

                    dt.Rows.Add(dr);
                }

                decimal saldoAnterior = 0;
                Invoice invoice = id.ultimoInvoice(Convert.ToInt32(qg.Quotation_Id));
                if (invoice != null)
                {
                    string retorno = ZeroNulo(invoice.Grand_Total.ToString());
                    saldoAnterior = Convert.ToDecimal(retorno);
                }

                inv.Grand_Total = saldoAnterior + grandTotal; //id.ultimoInvoice(Convert.ToInt32(qg.Quotation_Id)).Grand_Total;
                id.Salvar(inv);



                CrystalDecisions.CrystalReports.Engine.TextObject ObjGrandTotal = rpt.ReportDefinition.Sections[1].ReportObjects["txtGrandTotal"] as TextObject;
                ObjGrandTotal.Text = Convert.ToString(inv.Grand_Total);


                CrystalDecisions.CrystalReports.Engine.TextObject ObjTitulo = rpt.ReportDefinition.Sections[1].ReportObjects["txtTitulo"] as TextObject;
                ObjTitulo.Text = "INVOICE Nr:" + inv.Invoice_id.ToString();

                rpt.SetDataSource(dt);


                rpt.ExportToDisk(ExportFormatType.PortableDocFormat, fileName);

                switch (ddlFormato.SelectedValue)
                {
                    case "1":
                        rpt.ExportToHttpResponse(
                            ExportFormatType.PortableDocFormat,
                            Response, true, "invoice");
                        break;

                    case "2":
                        rpt.ExportToHttpResponse(
                            ExportFormatType.WordForWindows,
                            Response, true, "invoice");
                        break;

                    case "3":
                        rpt.ExportToHttpResponse(
                            ExportFormatType.Excel,
                            Response, true, "invoice");
                        break;
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        protected void EmitirRelatorioVoucherSouthAmerica()
        {
            string NomeEmpresa = ConfigurationManager.AppSettings["NomeEmpresa"];
            string EnderecoEmpresa = ConfigurationManager.AppSettings["EnderecoEmpresa"];
            string ContatoEmpresa = ConfigurationManager.AppSettings["ContatoEmpresa"];
            string UrlEmpresa = ConfigurationManager.AppSettings["UrlEmpresa"];

            ClienteDAL clid = new ClienteDAL();
            FileCarrinhoDAL fcd = new FileCarrinhoDAL();
            QuotationGrupoDAL qgd = new QuotationGrupoDAL();
            MoedaDAL moed = new MoedaDAL();
            SupplierDAL sd = new SupplierDAL();
            FileFlightsDAL ffDAL = new FileFlightsDAL();
            Supplier supplier = new Supplier();

            File_Carrinho fc = fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]));
            Quotation_Grupo qg = qgd.ObterPorId(fc.Quotation_Grupo_Id);
            DAL.Entity.Cliente cl = clid.ObterPorId(qg.Cliente_id);

            int IdFileCarrinho = fc.File_id;
            string moeda = moed.ObterPorId(Convert.ToInt32(qg.Moeda_id)).Moeda_sigla;
            List<string> lstPaises = new List<string>();
            string numEmergenciaPaises = "";

            File_Flights ff = new File_Flights();

            //Instanciando o DataSet
            DSVoucher ds = new DSVoucher();

            DataTable dt = ds.Tables["VOUCHER"];

            //Acessar a camada de persistência
            //FileTarifasDAL d = new FileTarifasDAL();

            QuoteTarifasDAL d = new QuoteTarifasDAL();

            // Criando um Dictionary para fazer a ordenação por data
            //Dictionary<DataRow, DateTime> dicOrdenacao = new Dictionary<DataRow,DateTime>();

            //dynamic objOrdenacao = new System.Dynamic.ExpandoObject();
            List<dynamic> lstOrdenacao = new List<dynamic>();

            //QuoteTarifasDAL d = new QuoteTarifasDAL();

            try
            {

                foreach (Quote_Tarifas p in d.ListarTodos(IdFileCarrinho))
                {
                    //Criar um novo registro dentro da DataTable
                    DataRow dr = dt.NewRow();
                    ff = ffDAL.ObterPorId(Convert.ToInt32(p.Flights_id));
                    supplier = sd.ObterPorId(Convert.ToInt32(p.S_id));

                    if (supplier.Cidade.Pais.PAIS_descricao != null)
                    {
                        bool existe = false;

                        foreach (string pais in lstPaises)
                            if (supplier.Cidade.Pais.PAIS_nome == pais)
                                existe = true;

                        if (!existe)
                        {
                            lstPaises.Add(supplier.Cidade.Pais.PAIS_nome);
                            numEmergenciaPaises += supplier.Cidade.Pais.PAIS_nome;
                            numEmergenciaPaises += (char)13;
                            numEmergenciaPaises += supplier.Cidade.Pais.PAIS_descricao;
                            numEmergenciaPaises += (char)13;
                            numEmergenciaPaises += (char)13;
                        }
                    }

                    dr["Supplier"] = supplier.S_nome;
                    dr["Endereco"] = supplier.S_endereco;
                    dr["Telefone"] = supplier.S_telefone;
                    dr["Email"] = supplier.S_email;

                    dr["Data"] = string.Format(new System.Globalization.CultureInfo("en-GB"), "{0:ddd, dd MMM}", p.Data_From) + " - " + string.Format(new System.Globalization.CultureInfo("en-GB"), "{0:ddd, dd MMM}", p.Data_To);

                    dr["Cidade"] = supplier.Cidade.CID_nome + " - " + new PaisDAL().ObterPorId((int)supplier.PAIS_id).PAIS_nome;

                    dr["Pax"] = p.Qtd_Tarifas;
                    dr["Flight"] = "";

                    dr["Servico"] = "";
                    if (ffDAL.ObterPorId(Convert.ToInt32(p.Flights_id)) != null)
                    {
                        string sServ = "";

                        if (!ff.Flights_nome.Trim().Equals(string.Empty))
                            sServ += "Flight: " + ff.Flights_nome;

                        if (!ff.Flights_hora.Trim().Equals(string.Empty))
                            if (sServ.Equals(string.Empty))
                                if ((ff.Flights_DataFrom != null) && ((bool)ff.Flights_DataFrom))
                                    sServ += "Arrives: " + ff.Flights_hora;
                                else
                                    sServ += "Departs: " + ff.Flights_hora;
                            else
                                if ((ff.Flights_DataFrom != null) && ((bool)ff.Flights_DataFrom))
                                    sServ += " / Arrives: " + ff.Flights_hora;
                                else
                                    sServ += " / Departs: " + ff.Flights_hora;

                        if (!ff.Flights_pickUp.Trim().Equals(string.Empty))
                            if (sServ.Equals(string.Empty))
                                sServ += "Pick Up Time: " + ff.Flights_pickUp;
                            else
                                sServ += " / Pick Up Time: " + ff.Flights_pickUp;

                        if (!ff.Flights_remarks.Trim().Equals(string.Empty))
                            if (sServ.Equals(string.Empty))
                                sServ += " " + ff.Flights_remarks;
                            else
                                sServ += " / " + ff.Flights_remarks;

                        if (sServ.Equals(string.Empty))
                            dr["Servico"] = p.S_nome + " - " + p.Categoria + " - " + p.Room + " / " + supplier.S_endereco + ", " + supplier.S_telefone;
                        else
                            dr["Servico"] = p.S_nome + " - " + p.Categoria + " - " + p.Room + " / " + supplier.S_endereco + ", " + supplier.S_telefone + (char)13 + sServ + (char)13;

                        if (!String.IsNullOrEmpty(ff.Flights_ConfirmationNbr)) 
                            if (dr["Servico"].ToString().Equals(string.Empty))
                                dr["Servico"] = "Confirmation Nbr:  " + ff.Flights_ConfirmationNbr;
                            else
                                dr["Servico"] = dr["Servico"] + " " + (char)13 + "Confirmation Nbr:  " + ff.Flights_ConfirmationNbr;
                        else
                            if (dr["Servico"].ToString().Equals(string.Empty))
                                dr["Servico"] = "Confirmation Nbr:  " + ff.Flights_ConfirmationNbr;
                            else
                                dr["Servico"] = dr["Servico"] + " " + (char)13 + "Confirmation Nbr:  " + (((qg.tourCode == null) || (qg.tourCode == "")) ? qg.Quotation_Id.ToString() : qg.tourCode.ToString() + " - " + qg.Quotation_Id.ToString());
                    }
                    else
                    {
                        //dr["Servico"] = dr["Servico"] + p.S_nome + " - " + p.Categoria + " - " + p.Room + " / " + supplier.S_endereco + ", " + supplier.S_telefone;
                        dr["Servico"] = dr["Servico"] + p.S_nome + "     " + "Address: " + supplier.S_endereco + "\r\n" + p.Categoria + " - " + p.Room + "      " + "Telephone: " + supplier.S_telefone;
                        dr["Servico"] = dr["Servico"] + " " + (char)13 + "Confirmation Nbr:  " + (qg.tourCode == null ? qg.Quotation_Id.ToString() : qg.tourCode.ToString() + " - " + qg.Quotation_Id.ToString());
                    }

                    //Gravo o registro
                    //dt.Rows.Add(dr);

                    lstOrdenacao.Add(new { Data = Convert.ToDateTime(p.Data_From), Row = dr, Ordenacao = 7 });
                    //dicOrdenacao.Add(dr, Convert.ToDateTime(p.Data_From));
                }

            }
            catch
            {
                throw;
            }

            //FileTransfersDAL ftd = new FileTransfersDAL();
            //FileTransfersDAL qtd = new FileTransfersDAL();

            try
            {

                QuoteTransDAL qtd = new QuoteTransDAL();
                foreach (Quote_Transf p in qtd.ListarTodos(IdFileCarrinho).Where(c => c.Range_id != 0))
                {
                    DataRow dr = dt.NewRow();
                    ff = ffDAL.ObterPorId(Convert.ToInt32(p.Flights_id));
                    supplier = sd.ObterPorId(Convert.ToInt32(p.S_id));

                    if (supplier.Cidade.Pais.PAIS_descricao != null)
                    {
                        bool existe = false;

                        foreach (string pais in lstPaises)
                            if (supplier.Cidade.Pais.PAIS_nome == pais)
                                existe = true;

                        if (!existe)
                        {
                            lstPaises.Add(supplier.Cidade.Pais.PAIS_nome);
                            numEmergenciaPaises += supplier.Cidade.Pais.PAIS_nome;
                            numEmergenciaPaises += (char)13;
                            numEmergenciaPaises += supplier.Cidade.Pais.PAIS_descricao;
                            numEmergenciaPaises += (char)13;
                            numEmergenciaPaises += (char)13;
                        }
                    }

                    dr["Supplier"] = supplier.S_nome;
                    dr["Endereco"] = supplier.S_endereco;
                    dr["Telefone"] = supplier.S_telefone;
                    dr["Email"] = supplier.S_email;

                    //Utils util = new Utils();                

                    dr["Data"] = string.Format(new System.Globalization.CultureInfo("en-GB"), "{0:ddd, dd MMM}", p.Data_From) + " - " + string.Format(new System.Globalization.CultureInfo("en-GB"), "{0:ddd, dd MMM}", p.Data_To);
                    dr["Cidade"] = sd.ObterPorId(Convert.ToInt32(p.S_id)).Cidade.CID_nome + " - " + new PaisDAL().ObterPorId((int)supplier.PAIS_id).PAIS_nome;
                    dr["Pax"] = p.Qtd_Transf;

                    if (ffDAL.ObterPorId(Convert.ToInt32(p.Flights_id)) != null)
                    {
                        string sServ = "";

                        if (!ff.Flights_nome.Trim().Equals(string.Empty))
                            sServ += "Flight: " + ff.Flights_nome;

                        if (!ff.Flights_hora.Trim().Equals(string.Empty))
                            if (sServ.Equals(string.Empty))
                                if ((ff.Flights_DataFrom != null) && ((bool)ff.Flights_DataFrom))
                                    sServ += "Arrives: " + ff.Flights_hora;
                                else
                                    sServ += "Departs: " + ff.Flights_hora;
                            else
                                if ((ff.Flights_DataFrom != null) && ((bool)ff.Flights_DataFrom))
                                    sServ += " / Arrives: " + ff.Flights_hora;
                                else
                                    sServ += " / Departs: " + ff.Flights_hora;

                        if (!ff.Flights_pickUp.Trim().Equals(string.Empty))
                            if (sServ.Equals(string.Empty))
                                sServ += "Pick Up Time: " + ff.Flights_pickUp;
                            else
                                sServ += " / Pick Up Time: " + ff.Flights_pickUp;

                        if (!ff.Flights_remarks.Trim().Equals(string.Empty))
                            if (sServ.Equals(string.Empty))
                                sServ += " " + ff.Flights_remarks;
                            else
                                sServ += " / " + ff.Flights_remarks;

                        if (sServ.Equals(string.Empty))
                            dr["Servico"] = p.Transf_nome + (((supplier.S_telefone == null) || (supplier.S_telefone.Equals(string.Empty))) ? "" : " - " + supplier.S_telefone) + (char)13;
                        else
                            dr["Servico"] = p.Transf_nome + (((supplier.S_telefone == null) || (supplier.S_telefone.Equals(string.Empty))) ? "" : " - " + supplier.S_telefone) + (char)13 + sServ + (char)13;

                        if ((p.Trf_Tours != null) && (!p.Trf_Tours.Equals("TRS")))
                        {
                            if (!String.IsNullOrEmpty(ff.Flights_ConfirmationNbr)) 
                                if (dr["Servico"].ToString().Equals(string.Empty))
                                    dr["Servico"] = "Flight Confirmation Nbr (PNR):  " + ff.Flights_ConfirmationNbr;
                                else
                                    dr["Servico"] = dr["Servico"] + " " + "Flight Confirmation Nbr (PNR):  " + ff.Flights_ConfirmationNbr;
                            else
                                if (dr["Servico"].ToString().Equals(string.Empty))
                                    dr["Servico"] = "Flight Confirmation Nbr (PNR):  " + ff.Flights_ConfirmationNbr;
                                else
                                    dr["Servico"] = dr["Servico"] + " " + "Flight Confirmation Nbr (PNR):  " + (((qg.tourCode == null) || (qg.tourCode == "")) ? qg.Quotation_Id.ToString() : qg.tourCode.ToString() + " - " + qg.Quotation_Id.ToString());
                        }
                    }
                    else
                    {
                        dr["Servico"] = p.Transf_nome + (supplier.S_telefone == "" ? "" : " - " + supplier.S_telefone);

                        if ((p.Trf_Tours != null) && (!p.Trf_Tours.Equals("TRS")))
                            dr["Servico"] = dr["Servico"] + " " + (char)13 + "Flight Confirmation Nbr (PNR):  " + (((qg.tourCode == null) || (qg.tourCode == "")) ? qg.Quotation_Id.ToString() : qg.tourCode.ToString() + " - " + qg.Quotation_Id.ToString());
                    }

                    var serv = new ServicoDAL().ObterPorNome(p.Transf_nome);
                    var stc = new ServicoTipoCategDAL().ObterPorId((int)serv.Tipo_categ_id);

                    switch (stc.Tipo_categ_id)
                    {
                        case 21:
                            lstOrdenacao.Add(new { Data = Convert.ToDateTime(p.Data_From), Row = dr, Ordenacao = 1 });
                            break;
                        case 20:
                            lstOrdenacao.Add(new { Data = Convert.ToDateTime(p.Data_From), Row = dr, Ordenacao = 2 });
                            break;
                        case 12:
                            lstOrdenacao.Add(new { Data = Convert.ToDateTime(p.Data_From), Row = dr, Ordenacao = 3 });
                            break;
                        case 10:
                            lstOrdenacao.Add(new { Data = Convert.ToDateTime(p.Data_From), Row = dr, Ordenacao = 4 });
                            break;
                        default:
                            lstOrdenacao.Add(new { Data = Convert.ToDateTime(p.Data_From), Row = dr, Ordenacao = 5 });
                            break;
                    }
                }
            }
            catch
            {

                throw;
            }

            //FileServExtraDAL fse = new FileServExtraDAL();
            //QuoteServExtDAL qse = new QuoteServExtDAL();

            try
            {

                QuoteServExtDAL fse = new QuoteServExtDAL();
                foreach (Quote_ServExtra fser in fse.ListarTodos(IdFileCarrinho))
                {
                    DataRow dr = dt.NewRow();
                    ff = ffDAL.ObterPorId(Convert.ToInt32(fser.Flights_id));
                    supplier = sd.ObterPorId(Convert.ToInt32(fser.S_id));

                    if (supplier.Cidade.Pais.PAIS_descricao != null)
                    {
                        bool existe = false;

                        foreach (string pais in lstPaises)
                            if (supplier.Cidade.Pais.PAIS_nome == pais)
                                existe = true;

                        if (!existe)
                        {
                            lstPaises.Add(supplier.Cidade.Pais.PAIS_nome);
                            numEmergenciaPaises += supplier.Cidade.Pais.PAIS_nome;
                            numEmergenciaPaises += (char)13;
                            numEmergenciaPaises += supplier.Cidade.Pais.PAIS_descricao;
                            numEmergenciaPaises += (char)13;
                            numEmergenciaPaises += (char)13;
                        }
                    }

                    dr["Supplier"] = supplier.S_nome;
                    dr["Endereco"] = supplier.S_endereco;
                    dr["Telefone"] = supplier.S_telefone;
                    dr["Email"] = supplier.S_email;
                    dr["Data"] = string.Format(new System.Globalization.CultureInfo("en-GB"), "{0:ddd, dd MMM}", fser.Data_From) + " - " + string.Format(new System.Globalization.CultureInfo("en-GB"), "{0:ddd, dd MMM}", fser.Data_To);
                    dr["Cidade"] = sd.ObterPorId(Convert.ToInt32(fser.S_id)).Cidade.CID_nome + " - " + new PaisDAL().ObterPorId((int)supplier.PAIS_id).PAIS_nome;

                    if (fser.Qtd_ServExtr == null) dr["Pax"] = 0; else dr["Pax"] = fser.Qtd_ServExtr;

                    if (ffDAL.ObterPorId(Convert.ToInt32(fser.Flights_id)) != null)
                    {
                        string sServ = "";

                        if (!ff.Flights_nome.Trim().Equals(string.Empty))
                            sServ += "Flight: " + ff.Flights_nome;

                        if (!ff.Flights_hora.Trim().Equals(string.Empty))
                            if (sServ.Equals(string.Empty))
                                if ((ff.Flights_DataFrom != null) && ((bool)ff.Flights_DataFrom))
                                    sServ += "Arrives: " + ff.Flights_hora;
                                else
                                    sServ += "Departs: " + ff.Flights_hora;
                            else
                                if ((ff.Flights_DataFrom != null) && ((bool)ff.Flights_DataFrom))
                                    sServ += " / Arrives: " + ff.Flights_hora;
                                else
                                    sServ += " / Departs: " + ff.Flights_hora;

                        if (!ff.Flights_pickUp.Trim().Equals(string.Empty))
                            if (sServ.Equals(string.Empty))
                                sServ += "Pick Up Time: " + ff.Flights_pickUp;
                            else
                                sServ += " / Pick Up Time: " + ff.Flights_pickUp;

                        if (!ff.Flights_remarks.Trim().Equals(string.Empty))
                            if (sServ.Equals(string.Empty))
                                sServ += " " + ff.Flights_remarks;
                            else
                                sServ += " / " + ff.Flights_remarks;

                        if (!sServ.Equals(string.Empty))
                            dr["Servico"] = fser.File_ServExtra_nome + " / " + supplier.S_telefone + (char)13 + sServ + (char)13;

                        if (!String.IsNullOrEmpty(ff.Flights_ConfirmationNbr)) 
                            if (dr["Servico"].ToString().Equals(string.Empty))
                                dr["Servico"] = "Confirmation Nbr:  " + ff.Flights_ConfirmationNbr;
                            else
                                dr["Servico"] = dr["Servico"] + " " + "Confirmation Nbr:  " + ff.Flights_ConfirmationNbr;
                        else
                            if (dr["Servico"].ToString().Equals(string.Empty))
                                dr["Servico"] = "Confirmation Nbr:  " + ff.Flights_ConfirmationNbr;
                            else
                                dr["Servico"] = dr["Servico"] + " " + "Confirmation Nbr:  " + (((qg.tourCode == null) || (qg.tourCode == "")) ? qg.Quotation_Id.ToString() : qg.tourCode.ToString() + " - " + qg.Quotation_Id.ToString());
                    }
                    else
                    {
                        dr["Servico"] = fser.File_ServExtra_nome + " / " + supplier.S_telefone;
                        dr["Servico"] = dr["Servico"] + " " + (char)13 + "Confirmation Nbr:  " + (((qg.tourCode == null) || (qg.tourCode == "")) ? qg.Quotation_Id.ToString() : qg.tourCode.ToString() + " - " + qg.Quotation_Id.ToString());
                    }


                    lstOrdenacao.Add(new { Data = Convert.ToDateTime(fser.Data_From), Row = dr, Ordenacao = 6 });
                }
            }
            catch
            {
                throw;
            }
            //Popular o Relatorio com os dados obtidos pela DataTable

            RptVoucher rpt = new RptVoucher();

            CrystalDecisions.CrystalReports.Engine.TextObject ObjTxtNomesTravelers = rpt.ReportDefinition.Sections[1].ReportObjects["txtNomesTravelers"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject ObjTxtAdl = rpt.ReportDefinition.Sections[1].ReportObjects["txtAdl"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject ObjTxtChl = rpt.ReportDefinition.Sections[1].ReportObjects["txtChl"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject ObjTxtInf = rpt.ReportDefinition.Sections[1].ReportObjects["txtInf"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject ObjTxtDataInOut = rpt.ReportDefinition.Sections[1].ReportObjects["txtDataInOut"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject objTxtEmergencyNumbers = rpt.ReportDefinition.Sections[1].ReportObjects["txtEmergencyNumbers"] as TextObject;

            objTxtEmergencyNumbers.Text = numEmergenciaPaises;

            CrystalDecisions.CrystalReports.Engine.TextObject ObjGrupoNome = rpt.ReportDefinition.Sections[1].ReportObjects["txtPaxGrupo"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject ObjPaxGroup = rpt.ReportDefinition.Sections[1].ReportObjects["txtPaxGroup"] as TextObject;
            CrystalDecisions.CrystalReports.Engine.TextObject ObjFileNumber = rpt.ReportDefinition.Sections[1].ReportObjects["txtNumeroFile"] as TextObject;

            CrystalDecisions.CrystalReports.Engine.TextObject objPrintDate = rpt.ReportDefinition.Sections[1].ReportObjects["txtPrintDate"] as TextObject;

            GrupoQtdAdultDAL gqa = new GrupoQtdAdultDAL();
            GrupoQtdChdDAL gqc = new GrupoQtdChdDAL();
            GrupoQtdInfDAL gqi = new GrupoQtdInfDAL();

            List<Quotation_Grupo_Qtd_Adult_Nome> listQgqan = gqa.ObterPorIdGrupo(qg.Quotation_Grupo_Id).Quotation_Grupo_Qtd_Adult_Nome.ToList();

            objPrintDate.Text = string.Format(new System.Globalization.CultureInfo("en-GB"), "{0:ddd, dd MMM}", DateTime.Now);

            string listaNomes = "";
            foreach (Quotation_Grupo_Qtd_Adult_Nome nome in listQgqan)
            {
                if (!nome.Nome.Equals(""))
                {
                    listaNomes = listaNomes + nome.Nome + ", ";
                }
            }

            ObjTxtNomesTravelers.Text = listaNomes;

            ObjTxtDataInOut.Text = string.Format(new System.Globalization.CultureInfo("en-GB"), "{0:ddd, dd MMM}", qg.dataIN) + " - " +
                string.Format(new System.Globalization.CultureInfo("en-GB"), "{0:ddd, dd MMM}", qg.dateOut); //  String.Format(qg.dataIN.ToString() + " - " + qg.dateOut.ToString();
            //ObjToCliente.Text = cl.Cliente_nome;
            ObjGrupoNome.Text = qg.Pax_Group_Name;
            ObjPaxGroup.Text = qg.Pax_Group_Name;

            if ((qg.tourCode == null) || (qg.tourCode == ""))
                ObjFileNumber.Text = qg.Quotation_Id.ToString();
            else
                ObjFileNumber.Text = qg.tourCode.ToString() + " - " + qg.Quotation_Id.ToString();

            ObjTxtAdl.Text = gqa.ObterPorIdGrupo(qg.Quotation_Grupo_Id).Qtd.ToString();
            ObjTxtChl.Text = gqc.ObterPorIdGrupo(qg.Quotation_Grupo_Id).Qtd.ToString();
            ObjTxtInf.Text = gqi.ObterPorIdGrupo(qg.Quotation_Grupo_Id).Qtd.ToString();
            //ObjQuotNumber.Text = qg.Quotation_Grupo_Id.ToString();

            lstOrdenacao = lstOrdenacao.OrderBy(a => a.Data).ToList();

            DateTime lastDate = new DateTime();

            List<dynamic> dRow = new List<dynamic>();
            List<dynamic> listaOrdenada = new List<dynamic>();

            for (int i = 0; i < lstOrdenacao.Count; i++)
            {
                DateTime data = lstOrdenacao[i].Data;

                if (data == lastDate)
                {
                    dRow.Add(lstOrdenacao[i]);

                    if (i == lstOrdenacao.Count - 1)
                        listaOrdenada.AddRange(dRow.OrderBy(a => a.Ordenacao).ToList());
                }
                else if ((dRow.Count == 1) || (dRow.Count == 0))
                {
                    if ((i < lstOrdenacao.Count - 1) && (lstOrdenacao[i + 1].Data == data))
                    {
                        dRow.Add(lstOrdenacao[i]);
                    }
                    else
                    {
                        dRow.Add(lstOrdenacao[i]);

                        listaOrdenada.AddRange(dRow);
                        dRow = new List<dynamic>();
                    }
                }
                else
                {
                    listaOrdenada.AddRange(dRow.OrderBy(a => a.Ordenacao).ToList());
                    dRow = new List<dynamic>();

                    dRow.Add(lstOrdenacao[i]);

                    if (i == lstOrdenacao.Count - 1)
                        listaOrdenada.Add(lstOrdenacao[i]);
                }

                lastDate = data;
            }

            dt = ds.Tables["VOUCHER"];

            foreach (dynamic item in listaOrdenada)
            {
                DataRow dataRow = dt.NewRow();

                dataRow["Data"] = item.Row["Data"];
                dataRow["Cidade"] = item.Row["Cidade"];
                dataRow["Servico"] = item.Row["Servico"];
                dataRow["Pax"] = item.Row["Pax"];
                dataRow["Flight"] = item.Row["Flight"];
                dataRow["Supplier"] = item.Row["Supplier"];
                dataRow["Endereco"] = item.Row["Endereco"];
                dataRow["Telefone"] = item.Row["Telefone"];
                dataRow["Email"] = item.Row["Email"];
                dataRow["Usuario"] = item.Row["Usuario"];
                dataRow["Linguagem"] = item.Row["Linguagem"];

                dt.Rows.Add(dataRow);
            }

            rpt.SetDataSource(dt);

            switch (ddlFormato.SelectedValue)
            {
                case "1":
                    rpt.ExportToHttpResponse(
                        ExportFormatType.PortableDocFormat,
                        Response, true, "voucher");
                    break;

                case "2":
                    rpt.ExportToHttpResponse(
                        ExportFormatType.WordForWindows,
                        Response, true, "voucher");
                    break;

                case "3":
                    rpt.ExportToHttpResponse(
                        ExportFormatType.Excel,
                        Response, true, "voucher");
                    break;
            }


        }

        private byte[] LoadImage(string path)
        {
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            byte[] img = new byte[fs.Length];
            fs.Read(img, 0, Convert.ToInt32(fs.Length));
            fs.Close();
            return img;
        }

        protected void EmitirRelatorioVoucher()
        {
            //try
            //{


            if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
            {
                EmitirRelatorioVoucherSouthAmerica();

            }
            else
            {


                string NomeEmpresa = ConfigurationManager.AppSettings["NomeEmpresa"];
                string EnderecoEmpresa = ConfigurationManager.AppSettings["EnderecoEmpresa"];
                string ContatoEmpresa = ConfigurationManager.AppSettings["ContatoEmpresa"];

                ClienteDAL clid = new ClienteDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();
                MoedaDAL moed = new MoedaDAL();
                SupplierDAL sd = new SupplierDAL();
                FileFlightsDAL ffDAL = new FileFlightsDAL();
                Supplier supplier = new Supplier();

                File_Carrinho fc = fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                Quotation_Grupo qg = qgd.ObterPorId(fc.Quotation_Grupo_Id);
                DAL.Entity.Cliente cl = clid.ObterPorId(qg.Cliente_id);

                int IdFileCarrinho = fc.File_id;
                string moeda = moed.ObterPorId(Convert.ToInt32(qg.Moeda_id)).Moeda_sigla;

                //Instanciando o DataSet
                DSVoucher ds = new DSVoucher();

                DataTable dt = ds.Tables["VOUCHER"];

                //Acessar a camada de persistência
                //FileTarifasDAL d = new FileTarifasDAL();

                QuoteTarifasDAL d = new QuoteTarifasDAL();

                foreach (Quote_Tarifas p in d.ListarTodos(IdFileCarrinho))
                {
                    //Criar um novo registro dentro da DataTable
                    DataRow dr = dt.NewRow();

                    supplier = sd.ObterPorId(Convert.ToInt32(p.S_id));

                    dr["Supplier"] = supplier.S_nome;
                    dr["Endereco"] = supplier.S_endereco;
                    dr["Telefone"] = supplier.S_telefone;
                    dr["Email"] = supplier.S_email;
                    dr["Data"] = string.Format("{0:dd.MM.yyyy}", p.Data_From) + " - " + string.Format("{0:dd.MM.yyyy}", p.Data_To);
                    dr["Cidade"] = supplier.Cidade.CID_cod_Iata; //sd.ObterPorId(Convert.ToInt32(p.S_id)).Cidade.CID_cod_Iata;
                    dr["Servico"] = p.S_nome + "     " + p.Categoria + " - " + p.Room; // +"   Paxs " + p.Qtd_Tarifas + "x";
                    dr["Pax"] = p.Qtd_Tarifas;

                    if (ffDAL.ObterPorId(Convert.ToInt32(p.Flights_id)) == null)
                    {
                        dr["Flight"] = "";
                    }
                    else
                    {
                        dr["Flight"] = ffDAL.ObterPorId(Convert.ToInt32(p.Flights_id)).Flights_nome;
                    }



                    //Gravo o registro
                    dt.Rows.Add(dr);
                }

                //FileTransfersDAL ftd = new FileTransfersDAL();

                QuoteTransDAL qtd = new QuoteTransDAL();

                foreach (Quote_Transf p in qtd.ListarTodos(IdFileCarrinho).Where(c => c.Range_id != 0))
                {
                    DataRow dr = dt.NewRow();

                    supplier = sd.ObterPorId(Convert.ToInt32(p.S_id));

                    dr["Supplier"] = supplier.S_nome;
                    dr["Endereco"] = supplier.S_endereco;
                    dr["Telefone"] = supplier.S_telefone;
                    dr["Email"] = supplier.S_email;

                    dr["Data"] = string.Format("{0:dd.MM.yyyy}", p.Data_From) + " - " + string.Format("{0:dd.MM.yyyy}", p.Data_To);
                    dr["Cidade"] = sd.ObterPorId(Convert.ToInt32(p.S_id)).Cidade.CID_cod_Iata;
                    dr["Servico"] = p.Transf_nome; // +"   Paxs " + p.Qtd_Transf + "x";
                    dr["Pax"] = p.Qtd_Transf;

                    if (ffDAL.ObterPorId(Convert.ToInt32(p.Flights_id)) == null)
                    {
                        dr["Flight"] = "";
                    }
                    else
                    {
                        dr["Flight"] = ffDAL.ObterPorId(Convert.ToInt32(p.Flights_id)).Flights_nome;
                    }

                    //Gravo o registro
                    dt.Rows.Add(dr);
                }

                QuoteServExtDAL qse = new QuoteServExtDAL();
                //FileServExtraDAL fse = new FileServExtraDAL();

                foreach (Quote_ServExtra fser in qse.ListarTodos(IdFileCarrinho))
                {
                    DataRow dr = dt.NewRow();

                    supplier = sd.ObterPorId(Convert.ToInt32(fser.S_id));

                    dr["Supplier"] = supplier.S_nome;
                    dr["Endereco"] = supplier.S_endereco;
                    dr["Telefone"] = supplier.S_telefone;
                    dr["Email"] = supplier.S_email;

                    dr["Data"] = string.Format("{0:dd.MM.yyyy}", fser.Data_From) + " - " + string.Format("{0:dd.MM.yyyy}", fser.Data_To);
                    dr["Cidade"] = sd.ObterPorId(Convert.ToInt32(fser.S_id)).Cidade.CID_cod_Iata;
                    dr["Servico"] = fser.File_ServExtra_nome;

                    if (fser.Qtd_ServExtr == null) dr["Pax"] = 0; else dr["Pax"] = fser.Qtd_ServExtr;

                    if (ffDAL.ObterPorId(Convert.ToInt32(fser.Flights_id)) == null)
                    {
                        dr["Flight"] = "";
                    }
                    else
                    {
                        dr["Flight"] = ffDAL.ObterPorId(Convert.ToInt32(fser.Flights_id)).Flights_nome;
                    }



                    //Gravo o registro
                    dt.Rows.Add(dr);
                }

                //Popular o Relatorio com os dados obtidos pela DataTable
                //RptVoucher rpt = new RptVoucher();           


                switch (ConfigurationManager.AppSettings["PuxaLogo"].ToString())
                {
                    case "Compass":
                        {
                            RptVoucherSupplier_Compass rpt = new RptVoucherSupplier_Compass();

                            CrystalDecisions.CrystalReports.Engine.TextObject ObjUsuario = rpt.ReportDefinition.Sections[1].ReportObjects["txtUsuario"] as TextObject;
                            CrystalDecisions.CrystalReports.Engine.TextObject ObjIdioma = rpt.ReportDefinition.Sections[1].ReportObjects["txtIdioma"] as TextObject;

                            CrystalDecisions.CrystalReports.Engine.TextObject ObjToCliente = rpt.ReportDefinition.Sections[1].ReportObjects["txtTo"] as TextObject;
                            CrystalDecisions.CrystalReports.Engine.TextObject ObjGrupoNome = rpt.ReportDefinition.Sections[1].ReportObjects["txtPaxGrp"] as TextObject;
                            CrystalDecisions.CrystalReports.Engine.TextObject ObjFileNumber = rpt.ReportDefinition.Sections[1].ReportObjects["txtFile"] as TextObject;
                            //CrystalDecisions.CrystalReports.Engine.TextObject ObjQuotNumber = rpt.ReportDefinition.Sections[1].ReportObjects["txtGrpId"] as TextObject;


                            //CrystalDecisions.CrystalReports.Engine.PictureObject obj = rpt.ReportDefinition.Sections[1].ReportObjects["txtFile"] as PictureObject;
                            //obj.



                            ObjUsuario.Text = qg.Usuarios.US_nome;
                            ObjIdioma.Text = qg.File_Liguagem.FLinguagem_nome;
                            ObjToCliente.Text = cl.Cliente_nome;
                            ObjGrupoNome.Text = qg.Pax_Group_Name;
                            ObjFileNumber.Text = qg.Quotation.Quotation_Code;
                            //ObjFileNumber.Text = qg.Quotation_Id.ToString();
                            //ObjQuotNumber.Text = qg.Quotation_Grupo_NGrupo;
                            //ObjQuotNumber.Text = qg.Quotation_Grupo_Id.ToString();

                            rpt.SetDataSource(dt);

                            switch (ddlFormato.SelectedValue)
                            {
                                case "1":
                                    rpt.ExportToHttpResponse(
                                        ExportFormatType.PortableDocFormat,
                                        Response, true, "voucher");
                                    break;

                                case "2":
                                    rpt.ExportToHttpResponse(
                                        ExportFormatType.WordForWindows,
                                        Response, true, "voucher");
                                    break;

                                case "3":
                                    rpt.ExportToHttpResponse(
                                        ExportFormatType.Excel,
                                        Response, true, "voucher");
                                    break;
                            }
                            break;
                        }

                    case "4Star":
                        {
                            RptVoucherSupplier_4Star rpt1 = new RptVoucherSupplier_4Star();

                            CrystalDecisions.CrystalReports.Engine.TextObject ObjUsuario1 = rpt1.ReportDefinition.Sections[1].ReportObjects["txtUsuario"] as TextObject;
                            CrystalDecisions.CrystalReports.Engine.TextObject ObjIdioma1 = rpt1.ReportDefinition.Sections[1].ReportObjects["txtIdioma"] as TextObject;

                            CrystalDecisions.CrystalReports.Engine.TextObject ObjToCliente1 = rpt1.ReportDefinition.Sections[1].ReportObjects["txtTo"] as TextObject;
                            CrystalDecisions.CrystalReports.Engine.TextObject ObjGrupoNome1 = rpt1.ReportDefinition.Sections[1].ReportObjects["txtPaxGrp"] as TextObject;
                            CrystalDecisions.CrystalReports.Engine.TextObject ObjFileNumber1 = rpt1.ReportDefinition.Sections[1].ReportObjects["txtFile"] as TextObject;
                            //CrystalDecisions.CrystalReports.Engine.TextObject ObjQuotNumber = rpt.ReportDefinition.Sections[1].ReportObjects["txtGrpId"] as TextObject;


                            //CrystalDecisions.CrystalReports.Engine.PictureObject obj = rpt.ReportDefinition.Sections[1].ReportObjects["txtFile"] as PictureObject;
                            //obj.



                            ObjUsuario1.Text = qg.Usuarios.US_nome;
                            ObjIdioma1.Text = qg.File_Liguagem.FLinguagem_nome;
                            ObjToCliente1.Text = cl.Cliente_nome;
                            ObjGrupoNome1.Text = qg.Pax_Group_Name;
                            ObjFileNumber1.Text = qg.Quotation.Quotation_Code;
                            //ObjFileNumber.Text = qg.Quotation_Id.ToString();
                            //ObjQuotNumber.Text = qg.Quotation_Grupo_NGrupo;
                            //ObjQuotNumber.Text = qg.Quotation_Grupo_Id.ToString();

                            rpt1.SetDataSource(dt);

                            switch (ddlFormato.SelectedValue)
                            {
                                case "1":
                                    rpt1.ExportToHttpResponse(
                                        ExportFormatType.PortableDocFormat,
                                        Response, true, "voucher");
                                    break;

                                case "2":
                                    rpt1.ExportToHttpResponse(
                                        ExportFormatType.WordForWindows,
                                        Response, true, "voucher");
                                    break;

                                case "3":
                                    rpt1.ExportToHttpResponse(
                                        ExportFormatType.Excel,
                                        Response, true, "voucher");
                                    break;
                            }
                            break;
                        }

                    case "DelBianco":
                        {
                            RptVoucherSupplier_DelBianco rpt2 = new RptVoucherSupplier_DelBianco();

                            CrystalDecisions.CrystalReports.Engine.TextObject ObjUsuario2 = rpt2.ReportDefinition.Sections[1].ReportObjects["txtUsuario"] as TextObject;
                            CrystalDecisions.CrystalReports.Engine.TextObject ObjIdioma2 = rpt2.ReportDefinition.Sections[1].ReportObjects["txtIdioma"] as TextObject;

                            CrystalDecisions.CrystalReports.Engine.TextObject ObjToCliente2 = rpt2.ReportDefinition.Sections[1].ReportObjects["txtTo"] as TextObject;
                            CrystalDecisions.CrystalReports.Engine.TextObject ObjGrupoNome2 = rpt2.ReportDefinition.Sections[1].ReportObjects["txtPaxGrp"] as TextObject;
                            CrystalDecisions.CrystalReports.Engine.TextObject ObjFileNumber2 = rpt2.ReportDefinition.Sections[1].ReportObjects["txtFile"] as TextObject;
                            //CrystalDecisions.CrystalReports.Engine.TextObject ObjQuotNumber = rpt.ReportDefinition.Sections[1].ReportObjects["txtGrpId"] as TextObject;


                            //CrystalDecisions.CrystalReports.Engine.PictureObject obj = rpt.ReportDefinition.Sections[1].ReportObjects["txtFile"] as PictureObject;
                            //obj.



                            ObjUsuario2.Text = qg.Usuarios.US_nome;
                            ObjIdioma2.Text = qg.File_Liguagem.FLinguagem_nome;
                            ObjToCliente2.Text = cl.Cliente_nome;
                            ObjGrupoNome2.Text = qg.Pax_Group_Name;
                            ObjFileNumber2.Text = qg.Quotation.Quotation_Code;
                            //ObjFileNumber.Text = qg.Quotation_Id.ToString();
                            //ObjQuotNumber.Text = qg.Quotation_Grupo_NGrupo;
                            //ObjQuotNumber.Text = qg.Quotation_Grupo_Id.ToString();

                            rpt2.SetDataSource(dt);

                            switch (ddlFormato.SelectedValue)
                            {
                                case "1":
                                    rpt2.ExportToHttpResponse(
                                        ExportFormatType.PortableDocFormat,
                                        Response, true, "voucher");
                                    break;

                                case "2":
                                    rpt2.ExportToHttpResponse(
                                        ExportFormatType.WordForWindows,
                                        Response, true, "voucher");
                                    break;

                                case "3":
                                    rpt2.ExportToHttpResponse(
                                        ExportFormatType.Excel,
                                        Response, true, "voucher");
                                    break;
                            }
                            break;
                        }
                    case "Rentamar":
                        {
                            RptVoucherSupplier_Rentamar rpt3 = new RptVoucherSupplier_Rentamar();

                            CrystalDecisions.CrystalReports.Engine.TextObject ObjUsuario3 = rpt3.ReportDefinition.Sections[1].ReportObjects["txtUsuario"] as TextObject;
                            CrystalDecisions.CrystalReports.Engine.TextObject ObjIdioma3 = rpt3.ReportDefinition.Sections[1].ReportObjects["txtIdioma"] as TextObject;

                            CrystalDecisions.CrystalReports.Engine.TextObject ObjToCliente3 = rpt3.ReportDefinition.Sections[1].ReportObjects["txtTo"] as TextObject;
                            CrystalDecisions.CrystalReports.Engine.TextObject ObjGrupoNome3 = rpt3.ReportDefinition.Sections[1].ReportObjects["txtPaxGrp"] as TextObject;
                            CrystalDecisions.CrystalReports.Engine.TextObject ObjFileNumber3 = rpt3.ReportDefinition.Sections[1].ReportObjects["txtFile"] as TextObject;
                            //CrystalDecisions.CrystalReports.Engine.TextObject ObjQuotNumber = rpt.ReportDefinition.Sections[1].ReportObjects["txtGrpId"] as TextObject;


                            //CrystalDecisions.CrystalReports.Engine.PictureObject obj = rpt.ReportDefinition.Sections[1].ReportObjects["txtFile"] as PictureObject;
                            //obj.



                            ObjUsuario3.Text = qg.Usuarios.US_nome;
                            ObjIdioma3.Text = qg.File_Liguagem.FLinguagem_nome;
                            ObjToCliente3.Text = cl.Cliente_nome;
                            ObjGrupoNome3.Text = qg.Pax_Group_Name;
                            ObjFileNumber3.Text = qg.Quotation.Quotation_Code;
                            //ObjFileNumber.Text = qg.Quotation_Id.ToString();
                            //ObjQuotNumber.Text = qg.Quotation_Grupo_NGrupo;
                            //ObjQuotNumber.Text = qg.Quotation_Grupo_Id.ToString();

                            rpt3.SetDataSource(dt);

                            switch (ddlFormato.SelectedValue)
                            {
                                case "1":
                                    rpt3.ExportToHttpResponse(
                                        ExportFormatType.PortableDocFormat,
                                        Response, true, "voucher");
                                    break;

                                case "2":
                                    rpt3.ExportToHttpResponse(
                                        ExportFormatType.WordForWindows,
                                        Response, true, "voucher");
                                    break;

                                case "3":
                                    rpt3.ExportToHttpResponse(
                                        ExportFormatType.Excel,
                                        Response, true, "voucher");
                                    break;
                            }
                            break;

                        }
                    case "ElcoTour":
                        {
                            RptVoucherSupplier_ElcoTour rpt3 = new RptVoucherSupplier_ElcoTour();

                            CrystalDecisions.CrystalReports.Engine.TextObject ObjUsuario3 = rpt3.ReportDefinition.Sections[1].ReportObjects["txtUsuario"] as TextObject;
                            CrystalDecisions.CrystalReports.Engine.TextObject ObjIdioma3 = rpt3.ReportDefinition.Sections[1].ReportObjects["txtIdioma"] as TextObject;

                            CrystalDecisions.CrystalReports.Engine.TextObject ObjToCliente3 = rpt3.ReportDefinition.Sections[1].ReportObjects["txtTo"] as TextObject;
                            CrystalDecisions.CrystalReports.Engine.TextObject ObjGrupoNome3 = rpt3.ReportDefinition.Sections[1].ReportObjects["txtPaxGrp"] as TextObject;
                            CrystalDecisions.CrystalReports.Engine.TextObject ObjFileNumber3 = rpt3.ReportDefinition.Sections[1].ReportObjects["txtFile"] as TextObject;
                            //CrystalDecisions.CrystalReports.Engine.TextObject ObjQuotNumber = rpt.ReportDefinition.Sections[1].ReportObjects["txtGrpId"] as TextObject;


                            //CrystalDecisions.CrystalReports.Engine.PictureObject obj = rpt.ReportDefinition.Sections[1].ReportObjects["txtFile"] as PictureObject;
                            //obj.



                            ObjUsuario3.Text = qg.Usuarios.US_nome;
                            ObjIdioma3.Text = qg.File_Liguagem.FLinguagem_nome;
                            ObjToCliente3.Text = cl.Cliente_nome;
                            ObjGrupoNome3.Text = qg.Pax_Group_Name;
                            ObjFileNumber3.Text = qg.Quotation.Quotation_Code;
                            //ObjFileNumber.Text = qg.Quotation_Id.ToString();
                            //ObjQuotNumber.Text = qg.Quotation_Grupo_NGrupo;
                            //ObjQuotNumber.Text = qg.Quotation_Grupo_Id.ToString();

                            rpt3.SetDataSource(dt);

                            switch (ddlFormato.SelectedValue)
                            {
                                case "1":
                                    rpt3.ExportToHttpResponse(
                                        ExportFormatType.PortableDocFormat,
                                        Response, true, "voucher");
                                    break;

                                case "2":
                                    rpt3.ExportToHttpResponse(
                                        ExportFormatType.WordForWindows,
                                        Response, true, "voucher");
                                    break;

                                case "3":
                                    rpt3.ExportToHttpResponse(
                                        ExportFormatType.Excel,
                                        Response, true, "voucher");
                                    break;
                            }

                            break;
                        }

                    case "ViaCapi":
                        {

                            RptVoucherSupplier_ViaCapi rpt3 = new RptVoucherSupplier_ViaCapi();

                            CrystalDecisions.CrystalReports.Engine.TextObject ObjUsuario3 = rpt3.ReportDefinition.Sections[1].ReportObjects["txtUsuario"] as TextObject;
                            CrystalDecisions.CrystalReports.Engine.TextObject ObjIdioma3 = rpt3.ReportDefinition.Sections[1].ReportObjects["txtIdioma"] as TextObject;

                            CrystalDecisions.CrystalReports.Engine.TextObject ObjToCliente3 = rpt3.ReportDefinition.Sections[1].ReportObjects["txtTo"] as TextObject;
                            CrystalDecisions.CrystalReports.Engine.TextObject ObjGrupoNome3 = rpt3.ReportDefinition.Sections[1].ReportObjects["txtPaxGrp"] as TextObject;
                            CrystalDecisions.CrystalReports.Engine.TextObject ObjFileNumber3 = rpt3.ReportDefinition.Sections[1].ReportObjects["txtFile"] as TextObject;
                            //CrystalDecisions.CrystalReports.Engine.TextObject ObjQuotNumber = rpt.ReportDefinition.Sections[1].ReportObjects["txtGrpId"] as TextObject;


                            //CrystalDecisions.CrystalReports.Engine.PictureObject obj = rpt.ReportDefinition.Sections[1].ReportObjects["txtFile"] as PictureObject;
                            //obj.



                            ObjUsuario3.Text = qg.Usuarios.US_nome;
                            ObjIdioma3.Text = qg.File_Liguagem.FLinguagem_nome;
                            ObjToCliente3.Text = cl.Cliente_nome;
                            ObjGrupoNome3.Text = qg.Pax_Group_Name;
                            ObjFileNumber3.Text = qg.Quotation.Quotation_Code;
                            //ObjFileNumber.Text = qg.Quotation_Id.ToString();
                            //ObjQuotNumber.Text = qg.Quotation_Grupo_NGrupo;
                            //ObjQuotNumber.Text = qg.Quotation_Grupo_Id.ToString();

                            rpt3.SetDataSource(dt);

                            switch (ddlFormato.SelectedValue)
                            {
                                case "1":
                                    rpt3.ExportToHttpResponse(
                                        ExportFormatType.PortableDocFormat,
                                        Response, true, "voucher");
                                    break;

                                case "2":
                                    rpt3.ExportToHttpResponse(
                                        ExportFormatType.WordForWindows,
                                        Response, true, "voucher");
                                    break;

                                case "3":
                                    rpt3.ExportToHttpResponse(
                                        ExportFormatType.Excel,
                                        Response, true, "voucher");
                                    break;
                            }

                            break;
                        }
                }

                //RptVoucherSupplier rpt = new RptVoucherSupplier();


            }


            //}
            //catch (Exception ex)
            //{
            //    System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
            //    Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

            //    MostrarMsg(ex.Message);
            //}
        }

        protected void EmitirRelatorioMapaServicos()
        {
            try
            {


                //Popular o Relatorio com os dados obtidos pela DataTable
                RptMapaServicos rpt = new RptMapaServicos();



                //Instanciando o DataSet
                DSMapaServicos ds = new DSMapaServicos();

                DataTable dt = ds.Tables["MapaServicos"];
                FileCarrinhoDAL fcDAL = new FileCarrinhoDAL();
                QuotationGrupoDAL qgDAL = new QuotationGrupoDAL();
                //FileTransfersDAL ftd = new FileTransfersDAL();
                QuoteTransDAL qtd = new QuoteTransDAL();
                FileFlightsDAL ffDAL = new FileFlightsDAL();
                CidadeDAL cDAL = new CidadeDAL();

                SupplierDAL sDAL = new SupplierDAL();

                foreach (Quote_Transf p in qtd.ListarTodos())
                {
                    DataRow dr = dt.NewRow();

                    dr["Numero_File"] = p.File_id;
                    dr["Quotation_Grupo"] = fcDAL.RetornaQuote(Convert.ToInt32(p.File_id));
                    int quote = fcDAL.RetornaQuote(Convert.ToInt32(p.File_id));

                    //dr["Pax_Grupo"] = qgDAL.ObterPorId(quote).Pax_Group_Name;
                    dr["Pax_Grupo"] = qgDAL.ObterPorIdQuotation(quote).Pax_Group_Name;
                    dr["Numero_Passageiros"] = p.Paxs;
                    dr["Cliente_File"] = qgDAL.ObterPorIdQuotation(fcDAL.RetornaQuote(Convert.ToInt32(p.File_id))).Cliente.Cliente_nome;
                    dr["Status"] = p.Status;
                    if (p.Flights_id != null)
                    {
                        dr["PickupAt"] = ffDAL.ObterPorId(Convert.ToInt32(p.Flights_id)).Flights_dropOff;
                        dr["flight"] = ffDAL.ObterPorId(Convert.ToInt32(p.Flights_id)).Flights_nome;
                        dr["hour"] = ffDAL.ObterPorId(Convert.ToInt32(p.Flights_id)).Flights_hora;
                    }
                    dr["Usuario"] = qgDAL.ObterPorIdQuotation(fcDAL.RetornaQuote(Convert.ToInt32(p.File_id))).Usuarios.US_nome;
                    dr["Idioma"] = qgDAL.ObterPorIdQuotation(fcDAL.RetornaQuote(Convert.ToInt32(p.File_id))).File_Liguagem.FLinguagem_nome;
                    dr["Nome_Servico"] = p.Transf_nome;
                    dr["Cidade"] = cDAL.ObterPorId(Convert.ToInt32(p.Trf_CID_id)).CID_nome;
                    dr["Data"] = p.Data_From;


                    //Gravo o registro
                    dt.Rows.Add(dr);
                }

                FileServExtraDAL fse = new FileServExtraDAL();
                QuoteServExtDAL qse = new QuoteServExtDAL();

                foreach (Quote_ServExtra fser in qse.ListarTodos())
                {
                    DataRow dr = dt.NewRow();

                    dr["Numero_File"] = fser.File_id;
                    dr["Quotation_Grupo"] = fcDAL.RetornaQuote(Convert.ToInt32(fser.File_id));
                    int quote = fcDAL.RetornaQuote(Convert.ToInt32(fser.File_id));

                    //dr["Pax_Grupo"] = qgDAL.ObterPorId(quote).Pax_Group_Name;
                    dr["Pax_Grupo"] = qgDAL.ObterPorIdQuotation(quote).Pax_Group_Name;
                    dr["Numero_Passageiros"] = fser.Paxs;
                    dr["Cliente_File"] = qgDAL.ObterPorIdQuotation(fcDAL.RetornaQuote(Convert.ToInt32(fser.File_id))).Cliente.Cliente_nome;
                    dr["Status"] = fser.Status;
                    if (fser.Flights_id != null)
                    {
                        dr["PickupAt"] = ffDAL.ObterPorId(Convert.ToInt32(fser.Flights_id)).Flights_dropOff;
                        dr["flight"] = ffDAL.ObterPorId(Convert.ToInt32(fser.Flights_id)).Flights_nome;
                        dr["hour"] = ffDAL.ObterPorId(Convert.ToInt32(fser.Flights_id)).Flights_hora;
                    }
                    dr["Usuario"] = qgDAL.ObterPorIdQuotation(fcDAL.RetornaQuote(Convert.ToInt32(fser.File_id))).Usuarios.US_nome;
                    dr["Idioma"] = qgDAL.ObterPorIdQuotation(fcDAL.RetornaQuote(Convert.ToInt32(fser.File_id))).File_Liguagem.FLinguagem_nome;

                    dr["Nome_Servico"] = fser.File_ServExtra_nome;
                    dr["Cidade"] = sDAL.ObterPorId(Convert.ToInt32(fser.S_id)).Cidade;//cDAL.ObterPorId(Convert.ToInt32(fser)).CID_nome;//cDAL.ObterPorId(Convert.ToInt32(p.Trf_CID_id)).CID_cod_Iata;
                    dr["Data"] = fser.Data_From;

                    //Gravo o registro
                    dt.Rows.Add(dr);
                }


                rpt.SetDataSource(dt);


                switch (ddlFormato.SelectedValue)
                {
                    case "1":
                        rpt.ExportToHttpResponse(
                            ExportFormatType.PortableDocFormat,
                            Response, true, "mapa de servicos");
                        break;

                    case "2":
                        rpt.ExportToHttpResponse(
                            ExportFormatType.WordForWindows,
                            Response, true, "mapa de servicos");
                        break;

                    case "3":
                        rpt.ExportToHttpResponse(
                            ExportFormatType.Excel,
                            Response, true, "mapa de servicos");
                        break;
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        public void SaveToOutput(Stream dataStream)
        {
            dataStream.Seek(0, SeekOrigin.Begin);

            string path = ("~/Invoices/");

            FileStream fileout = File.Create(Server.MapPath(path) + "file.pdf");

            const int chunk = 512;
            byte[] buffer = new byte[512];

            int bytesread = dataStream.Read(buffer, 0, chunk);

            while (bytesread == chunk)
            {
                HttpContext.Current.Response.OutputStream.Write(buffer, 0, chunk);
                fileout.Write(buffer, 0, chunk);
                bytesread = dataStream.Read(buffer, 0, chunk);
            }

            HttpContext.Current.Response.OutputStream.Write(buffer, 0, bytesread);
            fileout.Write(buffer, 0, bytesread);
            fileout.Close();

            HttpContext.Current.Response.ContentType = "application/pdf";
        }

        string ZeroNulo(string valor)
        {
            if (valor == null)
            {
                return "0";
            }
            else
            {
                return valor;
            }
        }

        #endregion

        #region Regras Carrinho

        protected void CalculaValorTotal()
        {
            try
            {
                double totalValorHotel = 0;
                double totalValorHotelVenda = 0;
                double totalValorHotelMarkup = 0;

                double totalValorServicos = 0;
                double totalValorServicosVenda = 0;
                double totalValorServicosMarkup = 0;

                double totalValorExtra = 0;
                double totalValorExtraVenda = 0;
                double totalValorExtraMarkup = 0;

                foreach (GridViewRow item in GridFileCarrinhoHoteis.Rows)
                {
                    TextBox txtValorTarifas = (TextBox)item.FindControl("txtValorTarifas");
                    TextBox txtVendaNet = (TextBox)item.FindControl("txtVendaNet");
                    TextBox txtVenda = (TextBox)item.FindControl("txtVenda");
                    TextBox txtQtdTarifas = (TextBox)item.FindControl("txtQtdTarifas");
                    Label lblNumNoites = (Label)item.FindControl("lblNumNoites");

                    double multvenda;

                    if (txtVenda.Text.Equals("") || txtVendaNet.Text.Equals(""))
                    {
                        multvenda = 0;
                    }
                    else
                    {
                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        {
                            multvenda = Convert.ToDouble(txtVenda.Text) * Convert.ToDouble(txtQtdTarifas.Text);
                        }
                        else
                        {
                            multvenda = Convert.ToDouble(txtVenda.Text) * Convert.ToDouble(txtQtdTarifas.Text);
                            //multvenda = Convert.ToDouble(txtVendaNet.Text) * Convert.ToDouble(txtQtdTarifas.Text);
                        }
                    }

                    double mult;

                    if (txtVenda.Text.Equals("") || txtVendaNet.Text.Equals(""))
                    {
                        mult = 0;
                    }
                    else
                    {
                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        {
                            mult = Convert.ToDouble(txtVendaNet.Text) * Convert.ToDouble(txtQtdTarifas.Text);
                        }
                        else
                        {
                            mult = Convert.ToDouble(txtValorTarifas.Text) * Convert.ToDouble(txtQtdTarifas.Text) * Convert.ToInt32(lblNumNoites.Text);
                        }
                    }

                    //double mult = Convert.ToDouble(txtValorTarifas.Text) * Convert.ToDouble(txtQtdTarifas.Text);

                    //totalValorHotel = totalValorHotel * Convert.ToInt32(lblNumNoites.Text);

                    totalValorHotel = totalValorHotel + mult;
                    totalValorHotelVenda = totalValorHotelVenda + multvenda;
                }

                foreach (GridViewRow item in GridFileCarrinhoTransfers.Rows)
                {
                    TextBox txtValorTarifas = (TextBox)item.FindControl("txtValorTarifas");
                    TextBox txtVendaNet = (TextBox)item.FindControl("txtVendaNet");
                    TextBox txtVenda = (TextBox)item.FindControl("txtVenda");
                    TextBox txtQtdTarifas = (TextBox)item.FindControl("txtQtdTarifas");

                    double multvenda;

                    if (txtVenda.Text.Equals("") || txtVendaNet.Text.Equals(""))
                    {
                        multvenda = 0;
                    }
                    else
                    {
                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        {
                            multvenda = Convert.ToDouble(txtVenda.Text) * Convert.ToDouble(txtQtdTarifas.Text);
                        }
                        else
                        {
                            multvenda = Convert.ToDouble(txtVenda.Text) * Convert.ToDouble(txtQtdTarifas.Text);
                            //multvenda = Convert.ToDouble(txtVendaNet.Text) * Convert.ToDouble(txtQtdTarifas.Text);
                        }
                    }

                    double mult;

                    if (txtVenda.Text.Equals("") || txtVendaNet.Text.Equals(""))
                    {
                        mult = 0;
                    }
                    else
                    {
                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        {
                            mult = Convert.ToDouble(txtVendaNet.Text) * Convert.ToDouble(txtQtdTarifas.Text);
                        }
                        else
                        {
                            mult = Convert.ToDouble(txtValorTarifas.Text) * Convert.ToDouble(txtQtdTarifas.Text);
                        }
                    }

                    totalValorServicos = totalValorServicos + mult;
                    totalValorServicosVenda = totalValorServicosVenda + multvenda;
                }

                foreach (GridViewRow item in GridFileCarrinhoExtras.Rows)
                {
                    TextBox txtValorTarifas = (TextBox)item.FindControl("txtValorTarifas");
                    TextBox txtVendaNet = (TextBox)item.FindControl("txtVendaNet");
                    TextBox txtVenda = (TextBox)item.FindControl("txtVenda");
                    TextBox txtQtdTarifas = (TextBox)item.FindControl("txtQtdTarifas");

                    if (!(txtValorTarifas.Text.Equals("") && txtVenda.Text.Equals("") && txtQtdTarifas.Text.Equals("")))
                    {

                        double multvenda;

                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        {
                            multvenda = Convert.ToDouble(txtVenda.Text) * Convert.ToDouble(txtQtdTarifas.Text);
                        }
                        else
                        {
                            multvenda = Convert.ToDouble(txtVenda.Text) * Convert.ToDouble(txtQtdTarifas.Text);
                            //multvenda = Convert.ToDouble(txtVendaNet.Text) * Convert.ToDouble(txtQtdTarifas.Text);
                        }
                        //double multvenda = Convert.ToDouble(txtVenda.Text) * Convert.ToDouble(txtQtdTarifas.Text);
                        //double mult = Convert.ToDouble(txtValorTarifas.Text) * Convert.ToDouble(txtQtdTarifas.Text);

                        double mult;

                        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        {
                            mult = Convert.ToDouble(txtVendaNet.Text) * Convert.ToDouble(txtQtdTarifas.Text);
                        }
                        else
                        {
                            mult = Convert.ToDouble(txtValorTarifas.Text) * Convert.ToDouble(txtQtdTarifas.Text);
                        }

                        totalValorExtra = totalValorExtra + mult;
                        totalValorExtraVenda = totalValorExtraVenda + multvenda;
                    }
                }

                if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                {
                    totalValorHotelMarkup = ((totalValorHotelVenda - totalValorHotel) / totalValorHotel) * 100;
                }
                else
                {
                    totalValorHotelMarkup = ((totalValorHotelVenda - totalValorHotel) * 100) / totalValorHotelVenda;
                }

                if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                {
                    totalValorServicosMarkup = (((totalValorServicosVenda + totalValorExtraVenda) - (totalValorServicos + totalValorExtra)) / (totalValorServicos + totalValorExtra)) * 100;
                }
                else
                {
                    totalValorServicosMarkup = (((totalValorServicosVenda + totalValorExtraVenda) - (totalValorServicos + totalValorExtra)) * 100) / (totalValorServicosVenda + totalValorExtraVenda);
                }

                totalValorExtraMarkup = ((totalValorExtraVenda - totalValorExtra) * 100) / totalValorExtraVenda;

                lblValorTotalHotelCarrinho.Text = totalValorHotel.ToString("N");
                lblValorTotalHotelCarrinhoVenda.Text = totalValorHotelVenda.ToString("N");
                lblValorTotalHotelMarkup.Text = totalValorHotelMarkup.ToString("N");

                lblValorTotalServicosCarrinho.Text = (totalValorServicos + totalValorExtra).ToString("N");
                lblValorTotalServicosCarrinhoVenda.Text = (totalValorServicosVenda + totalValorExtraVenda).ToString("N");
                lblValorTotalServicosCarrinhoMarkup.Text = totalValorServicosMarkup.ToString("N");

                lblValorGrandTotalCarrinho.Text = (totalValorHotel + totalValorServicos + totalValorExtra).ToString("N");
                lblValorGrandTotalCarrinhoVenda.Text = (totalValorHotelVenda + totalValorServicosVenda + totalValorExtraVenda).ToString("N");

                if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                {
                    lblValorGrandTotalCarrinhoMarkup.Text = (((Convert.ToDouble(lblValorGrandTotalCarrinhoVenda.Text) - Convert.ToDouble(lblValorGrandTotalCarrinho.Text)) / Convert.ToDouble(lblValorGrandTotalCarrinho.Text)) * 100).ToString("N");
                }
                else
                {
                    lblValorGrandTotalCarrinhoMarkup.Text = (((Convert.ToDouble(lblValorGrandTotalCarrinhoVenda.Text) - Convert.ToDouble(lblValorGrandTotalCarrinho.Text)) * 100) / Convert.ToDouble(lblValorGrandTotalCarrinhoVenda.Text)).ToString("N");
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                lblMsgCadQuotatio.Text = ex.Message;
            }
        }

        protected void OpenFlightsNew(object sender, CommandEventArgs e)
        {
            try
            {
                string[] pars = e.CommandArgument.ToString().Split(',');

                if (pars[1].ToString().Equals("hotel"))
                {
                    ViewState["IdFileHotelFlight"] = Convert.ToInt32(pars[0]);
                    ViewState["IdFileServExtraFlight"] = "";
                    ViewState["IdFileServicoFlight"] = "";
                }
                else if (pars[1].ToString().Equals("servico"))
                {
                    ViewState["IdFileServicoFlight"] = Convert.ToInt32(pars[0]);
                    ViewState["IdFileServExtraFlight"] = "";
                    ViewState["IdFileHotelFlight"] = "";
                }
                else if (pars[1].ToString().Equals("extra"))
                {
                    ViewState["IdFileServExtraFlight"] = Convert.ToInt32(pars[0]);
                    ViewState["IdFileServicoFlight"] = "";
                    ViewState["IdFileHotelFlight"] = "";
                }

                txtConfirmationNumber.Text = "";

                if (pars[2].Equals("Quote"))
                {
                    VerificaFlight();
                    btnSalvarFlight.Visible = true;
                    btnSalvarFlightNew.Visible = false;
                }
                else
                {
                    btnSalvarFlight.Visible = false;
                    btnSalvarFlightNew.Visible = true;
                    VerificaFlightNew();
                }

                ModalPopupExtenderFlights.Show();

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void OpenFlightsHoteis(object sender, CommandEventArgs e)
        {
            try
            {
                ViewState["IdFileServicoFlight"] = "";
                ViewState["IdFileServExtraFlight"] = "";

                ViewState["IdFileHotelFlight"] = Convert.ToInt32(e.CommandArgument);

                lblConfirmationNumber.Visible = true;
                txtConfirmationNumber.Visible = true;
                txtConfirmationNumber.Text = "";


                VerificaFlight();

                ModalPopupExtenderFlights.Show();

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void OpenFlightsServico(object sender, CommandEventArgs e)
        {
            try
            {

                ViewState["IdFileHotelFlight"] = "";
                ViewState["IdFileServExtraFlight"] = "";

                ViewState["IdFileServicoFlight"] = Convert.ToInt32(e.CommandArgument);

                txtConfirmationNumber.Text = "";
                VerificaFlight();

                ModalPopupExtenderFlights.Show();

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void OpenFlightsServExtra(object sender, CommandEventArgs e)
        {
            try
            {
                ViewState["IdFileHotelFlight"] = "";
                ViewState["IdFileServicoFlight"] = "";

                ViewState["IdFileServExtraFlight"] = Convert.ToInt32(e.CommandArgument);

                lblConfirmationNumber.Visible = false;
                txtConfirmationNumber.Visible = false;
                txtConfirmationNumber.Text = "";

                VerificaFlight();

                ModalPopupExtenderFlights.Show();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void VerificaBulkGrade(object sender, CommandEventArgs e)
        {
            try
            {
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileTransfersDAL ftrd = new FileTransfersDAL();
                FileServExtraDAL fsed = new FileServExtraDAL();

                string[] pars = e.CommandArgument.ToString().Split(',');

                bool bulk;

                if (pars[1].Equals("") || Convert.ToBoolean(pars[1]) == false) bulk = false; else bulk = true;


                switch (pars[2].ToString())
                {
                    case "hotel":

                        File_Tarifas ft = new File_Tarifas();

                        if (bulk)
                        {
                            ft.File_Tarifas_id = Convert.ToInt32(pars[0]);
                            ft.TBulk = false;
                        }
                        else
                        {
                            ft.File_Tarifas_id = Convert.ToInt32(pars[0]);
                            ft.TBulk = true;
                        }

                        ftd.AtualizarBulk(ft);

                        break;

                    case "servico":

                        File_Transfers ftr = new File_Transfers();

                        if (bulk)
                        {
                            ftr.File_Transf_id = Convert.ToInt32(pars[0]);
                            ftr.TBulk = false;
                        }
                        else
                        {
                            ftr.File_Transf_id = Convert.ToInt32(pars[0]);
                            ftr.TBulk = true;
                        }

                        ftrd.AtualizarBulk(ftr);


                        break;

                    case "extra":

                        File_ServExtra fsex = new File_ServExtra();

                        if (bulk)
                        {
                            fsex.File_ServExtra_id = Convert.ToInt32(pars[0]);
                            fsex.TBulk = false;
                        }
                        else
                        {
                            fsex.File_ServExtra_id = Convert.ToInt32(pars[0]);
                            fsex.TBulk = true;
                        }

                        fsed.AtualizarBulk(fsex);

                        break;
                }

                MostrarMsg("Tarifa alterada com sucesso.");
                CarregarFileNumero(sender, e);
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        protected void OpenPaxsNew(object sender, CommandEventArgs e)
        {
            try
            {
                string[] pars = e.CommandArgument.ToString().Split(',');

                if (pars[1].ToString().Equals("hotel"))
                {
                    ViewState["IdFilePaxsHoteis"] = Convert.ToInt32(pars[0]);
                    ViewState["IdFilePaxsServExtras"] = "";
                    ViewState["IdFilePaxsServicos"] = "";
                }
                else if (pars[1].ToString().Equals("servico"))
                {
                    ViewState["IdFilePaxsServicos"] = Convert.ToInt32(pars[0]);
                    ViewState["IdFilePaxsServExtras"] = "";
                    ViewState["IdFilePaxsHoteis"] = "";
                }
                else if (pars[1].ToString().Equals("extra"))
                {
                    ViewState["IdFilePaxsServExtras"] = Convert.ToInt32(pars[0]);
                    ViewState["IdFilePaxsServicos"] = "";
                    ViewState["IdFilePaxsHoteis"] = "";
                }

                //ViewState["IdFilePaxsServExtras"] = "";
                //ViewState["IdFilePaxsServicos"] = "";
                //ViewState["IdFilePaxsHoteis"] = Convert.ToInt32(e.CommandArgument);

                VerificaPaxs();

                ModalPopupExtenderPaxs.Show();

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void OpenPaxsHoteis(object sender, CommandEventArgs e)
        {
            try
            {
                ViewState["IdFilePaxsServExtras"] = "";
                ViewState["IdFilePaxsServicos"] = "";
                ViewState["IdFilePaxsHoteis"] = Convert.ToInt32(e.CommandArgument);

                VerificaPaxs();

                ModalPopupExtenderPaxs.Show();

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void OpenPaxsServicos(object sender, CommandEventArgs e)
        {
            try
            {
                ViewState["IdFilePaxsServExtras"] = "";
                ViewState["IdFilePaxsHoteis"] = "";
                ViewState["IdFilePaxsServicos"] = Convert.ToInt32(e.CommandArgument);

                VerificaPaxs();

                ModalPopupExtenderPaxs.Show();

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void OpenPaxsServExtras(object sender, CommandEventArgs e)
        {
            try
            {
                ViewState["IdFilePaxsServicos"] = "";
                ViewState["IdFilePaxsHoteis"] = "";
                ViewState["IdFilePaxsServExtras"] = Convert.ToInt32(e.CommandArgument);

                VerificaPaxs();

                ModalPopupExtenderPaxs.Show();

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnAddNumDiasCarrinho_Click(object sender, EventArgs e)
        {

            try
            {
                FileCarrinhoDAL fcarr = new FileCarrinhoDAL();

                if (chkAddNumDiasCarrinho.Checked)
                {


                    FileTarifasDAL ftd = new FileTarifasDAL();

                    foreach (GridViewRow item in GridFileCarrinhoHoteis.Rows)
                    {
                        Label IdFileTarifa = (Label)item.FindControl("IdFileTarifa");

                        File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(IdFileTarifa.Text));

                        if (ft.Ordem >= Convert.ToInt32(ViewState["AddDiasOrdem"]))
                        {
                            File_Tarifas ftnew = new File_Tarifas();

                            ftnew.Data_From = Convert.ToDateTime(ft.Data_From).AddDays(Convert.ToInt32(txtNumDiasAddCarrinho.Text));
                            ftnew.Data_To = Convert.ToDateTime(ft.Data_To).AddDays(Convert.ToInt32(txtNumDiasAddCarrinho.Text));
                            ftnew.File_Tarifas_id = ft.File_Tarifas_id;

                            ftd.AtualizarDatas(ftnew);
                        }

                    }


                    FileTransfersDAL ftrd = new FileTransfersDAL();

                    foreach (GridViewRow item in GridFileCarrinhoTransfers.Rows)
                    {
                        Label IdFileTarifa = (Label)item.FindControl("IdFileTarifa");

                        File_Transfers ft = ftrd.ObterPorId(Convert.ToInt32(IdFileTarifa.Text));

                        if (ft.Ordem >= Convert.ToInt32(ViewState["AddDiasOrdem"]))
                        {
                            File_Transfers ftnew = new File_Transfers();

                            ftnew.Data_From = Convert.ToDateTime(ft.Data_From).AddDays(Convert.ToInt32(txtNumDiasAddCarrinho.Text));
                            ftnew.Data_To = Convert.ToDateTime(ft.Data_To).AddDays(Convert.ToInt32(txtNumDiasAddCarrinho.Text));
                            ftnew.File_Transf_id = ft.File_Transf_id;

                            ftrd.AtualizarDatas(ftnew);
                        }

                    }



                    FileServExtraDAL fsd = new FileServExtraDAL();

                    foreach (GridViewRow item in GridFileCarrinhoExtras.Rows)
                    {
                        Label IdFileServExtra = (Label)item.FindControl("IdFileServExtra");

                        File_ServExtra ft = fsd.ObterPorId(Convert.ToInt32(IdFileServExtra.Text));

                        if (ft.Ordem >= Convert.ToInt32(ViewState["AddDiasOrdem"]))
                        {
                            File_ServExtra ftnew = new File_ServExtra();

                            ftnew.Data_From = Convert.ToDateTime(ft.Data_From).AddDays(Convert.ToInt32(txtNumDiasAddCarrinho.Text));
                            ftnew.Data_To = Convert.ToDateTime(ft.Data_To).AddDays(Convert.ToInt32(txtNumDiasAddCarrinho.Text));
                            ftnew.File_ServExtra_id = ft.File_ServExtra_id;

                            fsd.AtualizarDatas(ftnew);
                        }

                    }

                    PopularGridListCarrinhoExtras(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                    PopularGridListCarrinhoTransfers(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                    PopularGridListCarrinho(Convert.ToInt32(ViewState["IdQuotGrupo"]));

                }
                else
                {
                    switch (ViewState["AddDiasTipo"].ToString())
                    {
                        case "hotel":

                            FileTarifasDAL ftd = new FileTarifasDAL();

                            File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(ViewState["AddDiasId"]));

                            File_Tarifas ftnew = new File_Tarifas();

                            ftnew.Data_From = Convert.ToDateTime(ft.Data_From).AddDays(Convert.ToInt32(txtNumDiasAddCarrinho.Text));
                            ftnew.Data_To = Convert.ToDateTime(ft.Data_To).AddDays(Convert.ToInt32(txtNumDiasAddCarrinho.Text));
                            ftnew.File_Tarifas_id = ft.File_Tarifas_id;

                            ftd.AtualizarDatas(ftnew);

                            PopularGridListCarrinho(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                            break;

                        case "transfer":

                            FileTransfersDAL ftrd = new FileTransfersDAL();

                            File_Transfers ftr = ftrd.ObterPorId(Convert.ToInt32(ViewState["AddDiasId"]));

                            File_Transfers ftrnew = new File_Transfers();

                            ftrnew.Data_From = Convert.ToDateTime(ftr.Data_From).AddDays(Convert.ToInt32(txtNumDiasAddCarrinho.Text));
                            ftrnew.Data_To = Convert.ToDateTime(ftr.Data_To).AddDays(Convert.ToInt32(txtNumDiasAddCarrinho.Text));
                            ftrnew.File_Transf_id = ftr.File_Transf_id;

                            ftrd.AtualizarDatas(ftrnew);

                            PopularGridListCarrinhoTransfers(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                            break;

                        case "extra":

                            FileServExtraDAL fsd = new FileServExtraDAL();

                            File_ServExtra fse = fsd.ObterPorId(Convert.ToInt32(ViewState["AddDiasId"]));

                            File_ServExtra fsenew = new File_ServExtra();

                            fsenew.Data_From = Convert.ToDateTime(fse.Data_From).AddDays(Convert.ToInt32(txtNumDiasAddCarrinho.Text));
                            fsenew.Data_To = Convert.ToDateTime(fse.Data_To).AddDays(Convert.ToInt32(txtNumDiasAddCarrinho.Text));
                            fsenew.File_ServExtra_id = fse.File_ServExtra_id;

                            fsd.AtualizarDatas(fsenew);

                            PopularGridListCarrinhoExtras(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                            break;
                    }
                }

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }

        }

        #endregion

        #region Regras Email

        protected void ddlTipoEnvioEmail_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlTipoEnvioEmail.SelectedValue.Equals("1"))
            {
                PopulaDropSupplierEmailsHoteis();
                MontaEmailHoteis();
                EditorEmail.Visible = true;
                btnEnviarEmail.Visible = true;
                lblEmailNovo.Visible = true;
                txtEmailNovo.Visible = true;
            }
            else
            {
                PopulaDropSupplierEmailsServicos();
                MontaEmailServicos();
                EditorEmail.Visible = true;
                btnEnviarEmail.Visible = true;
                lblEmailNovo.Visible = true;
                txtEmailNovo.Visible = true;
            }

        }

        protected void ddlSupplierEmails_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlTipoEnvioEmail.SelectedValue.Equals("1"))
            {
                MontaEmailHoteis();
            }
            else
            {
                MontaEmailServicos();
            }
        }

        protected void PopulaDropSupplierEmailsHoteis()
        {
            try
            {
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                ddlSupplierEmails.DataSource = ftd.ListarTodosSuppliers(fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])).File_id);
                ddlSupplierEmails.DataTextField = "S_nome";
                ddlSupplierEmails.DataValueField = "S_id";
                ddlSupplierEmails.DataBind();

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        protected void PopulaDropSupplierEmailsServicos()
        {
            try
            {

                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                FileTransfersDAL ftd = new FileTransfersDAL();

                ddlSupplierEmails.DataSource = ftd.ListarTodos(fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"])).File_id);
                ddlSupplierEmails.DataTextField = "S_nome";
                ddlSupplierEmails.DataValueField = "S_id";
                ddlSupplierEmails.DataBind();

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        protected void MontaEmailHoteis()
        {
            try
            {
                ClienteDAL clid = new ClienteDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();
                FileTarifasDAL ftd = new FileTarifasDAL();
                MoedaDAL moed = new MoedaDAL();
                SupplierDAL sd = new SupplierDAL();
                EmailDAL emd = new EmailDAL();
                UsuarioDAL usd = new UsuarioDAL();

                File_Carrinho fc = fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                Quotation_Grupo qg = qgd.ObterPorId(fc.Quotation_Grupo_Id);
                DAL.Entity.Cliente cl = clid.ObterPorId(qg.Cliente_id);
                Supplier s = sd.ObterPorId(Convert.ToInt32(ddlSupplierEmails.SelectedValue));
                List<File_Tarifas> listaHoteis = ftd.ListarTodos(fc.File_id, Convert.ToInt32(ddlSupplierEmails.SelectedValue));
                Email email = emd.ObterPorTipoSupp(1);
                Usuario user = usd.ObterPorId(qg.US_id);

                string Header = "";
                Header = Header + "<span style=\"font-weight: bold;\">Rio de Janeiro " + DateTime.Now.ToString("dd.MM.yyyy") + "</span><br/><br/>";
                Header = Header + "Para: <span style=\"font-weight: bold;\">" + s.S_nome + "</span><br/><br/>";
                Header = Header + "Referente: File <span style=\"font-weight: bold;\">" + qg.Quotation_Id.ToString() + "/" + qg.Quotation_Grupo_Id.ToString() + "</span> - <span style=\"font-weight: bold;color: #ff0000;\">" + qg.Pax_Group_Name + "</span><br/><br/>";
                Header = Header + "Idioma: <span style=\"font-weight: bold;\">" + qg.File_Liguagem.FLinguagem_nome + "</span><br/><br/>";
                Header = Header + "<span style=\"text-decoration: underline;\">Solicitamos a seguinte reserva:</span>";

                Header = Header + "<br/><br/>";

                foreach (File_Tarifas ft in listaHoteis)
                {
                    Header = Header + "Check In: <span style=\"font-weight: bold;\">" + string.Format("{0:dd/MM/yyyy}", ft.Data_From) + "</span> -- ";
                    Header = Header + "Check Out: <span style=\"font-weight: bold;\">" + string.Format("{0:dd/MM/yyyy}", ft.Data_To) + "   </span><span style=\"font-weight: bold;color: #ff0000;\">" + ft.Qtd_Tarifas + "x " + ft.Categoria + " " + ft.Room + "</span></br></br>";
                }

                Header = Header + email.Email_Obs;
                Header = Header + user.US_nome;

                EditorEmail.Content = Header;

                txtEmailNovo.Text = s.S_email;

            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);


                MostrarMsg(ex.Message);
            }
        }

        protected void MontaEmailServicos()
        {
            try
            {
                ClienteDAL clid = new ClienteDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();
                FileTransfersDAL ftd = new FileTransfersDAL();
                FileServExtraDAL fsed = new FileServExtraDAL();
                MoedaDAL moed = new MoedaDAL();
                SupplierDAL sd = new SupplierDAL();
                EmailDAL emd = new EmailDAL();
                UsuarioDAL usd = new UsuarioDAL();

                File_Carrinho fc = fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                Quotation_Grupo qg = qgd.ObterPorId(fc.Quotation_Grupo_Id);
                DAL.Entity.Cliente cl = clid.ObterPorId(qg.Cliente_id);
                Supplier s = sd.ObterPorId(Convert.ToInt32(ddlSupplierEmails.SelectedValue));
                List<File_Transfers> listaServicos = ftd.ListarTodos(fc.File_id, Convert.ToInt32(ddlSupplierEmails.SelectedValue));
                List<File_ServExtra> listaServExtras = fsed.ListarTodos(fc.File_id, Convert.ToInt32(ddlSupplierEmails.SelectedValue));
                Email email = emd.ObterPorTipoSupp(1);
                Usuario user = usd.ObterPorId(qg.US_id);

                string Header = "";
                Header = Header + "<span style=\"font-weight: bold;\">Rio de Janeiro " + DateTime.Now.ToString("dd.MM.yyyy") + "</span><br/><br/>";
                Header = Header + "Para: <span style=\"font-weight: bold;\">" + s.S_nome + "</span><br/><br/>";
                Header = Header + "Referente: File <span style=\"font-weight: bold;\">" + qg.Quotation_Id.ToString() + "/" + qg.Quotation_Grupo_Id.ToString() + "</span> - <span style=\"font-weight: bold;color: #ff0000;\">" + qg.Pax_Group_Name + "</span><br/><br/>";
                Header = Header + "Idioma: <span style=\"font-weight: bold;\">" + qg.File_Liguagem.FLinguagem_nome + "</span><br/><br/>";
                Header = Header + "<span style=\"text-decoration: underline;\">Solicitamos a seguinte reserva:</span>";

                Header = Header + "<br/><br/>";

                foreach (File_Transfers ft in listaServicos)
                {
                    Header = Header + "Check In: <span style=\"font-weight: bold;\">" + string.Format("{0:dd/MM/yyyy}", ft.Data_From) + "</span> -- ";
                    Header = Header + "Check Out: <span style=\"font-weight: bold;\">" + string.Format("{0:dd/MM/yyyy}", ft.Data_To) + "   </span><span style=\"font-weight: bold;color: #ff0000;\">" + ft.Qtd_Transf + "x " + ft.Transf_nome + "</span></br></br>";
                }

                foreach (File_ServExtra ft in listaServExtras)
                {
                    Header = Header + "Check In: <span style=\"font-weight: bold;\">" + string.Format("{0:dd/MM/yyyy}", ft.Data_From) + "</span> -- ";
                    Header = Header + "Check Out: <span style=\"font-weight: bold;\">" + string.Format("{0:dd/MM/yyyy}", ft.Data_To) + "   </span><span style=\"font-weight: bold;color: #ff0000;\">" + ft.Qtd_ServExtr + "x " + ft.File_ServExtra_nome + "</span></br></br>";
                }

                Header = Header + email.Email_Obs;
                Header = Header + user.US_nome;

                EditorEmail.Content = Header;

                txtEmailNovo.Text = s.S_email;


            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);


                MostrarMsg(ex.Message);
            }
        }

        protected void btnEnviarEmail_Click(object sender, EventArgs e)
        {
            try
            {
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();
                FileTarifasDAL ftd = new FileTarifasDAL();
                SupplierDAL sd = new SupplierDAL();
                Emails email = new Emails();

                File_Carrinho fc = fcd.ObterPorIdGrupo(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                Quotation_Grupo qg = qgd.ObterPorId(fc.Quotation_Grupo_Id);
                Supplier s = sd.ObterPorId(Convert.ToInt32(ddlSupplierEmails.SelectedValue));

                //List<File_Tarifas> listaHoteis = ftd.ListarTodos(fc.File_id, Convert.ToInt32(ddlSupplierEmails.SelectedValue));

                //email.EnviarMensagem(s.S_email, "Confirmar Reserva", EditorEmail.Content);

                email.EnviarMensagem(txtEmailNovo.Text.Trim(), "Confirmar Reserva", EditorEmail.Content);

                MostrarMsg("Email enviado com sucesso.");
            }
            catch (Exception ex)
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Log.Save((trace.GetFrame(0).GetMethod().ReflectedType.FullName), ("Linha: " + trace.GetFrame(0).GetFileLineNumber()), ("Column: " + trace.GetFrame(0).GetFileColumnNumber()), ex.Message);

                MostrarMsg(ex.Message);
            }
        }

        #endregion

        #region Regras Flights

        protected void lnkEscreverCidade_Click(object sender, EventArgs e)
        {

            SelectCidade(1);

            ModalPopupExtenderFlights.Show();
        }

        protected void lnkEscreverCidadeCancelar_Click(object sender, EventArgs e)
        {
            SelectCidade(0);

            ModalPopupExtenderFlights.Show();
        }

        protected void SelectCidade(int insert)
        {
            if (insert == 1)
            {
                ddlCidadeFlights.SelectedValue = "0";
                ddlCidadeFlights.Visible = false;
                txtCidadeFlights.Visible = true;
                lnkEscreverCidade.Visible = false;
                lnkEscreverCidadeCancelar.Visible = true;
            }
            else
            {
                ddlCidadeFlights.Visible = true;
                txtCidadeFlights.Text = "";
                txtCidadeFlights.Visible = false;
                lnkEscreverCidade.Visible = true;
                lnkEscreverCidadeCancelar.Visible = false;
            }
        }

        protected void LimpaTelaFlight()
        {
            PopularDropCidadeFlights();
            SelectCidade(0);
            txtFlight.Text = "";
            txtHoraFlight.Text = "";
            txtPickUpFlight.Text = "";
            txtDropOffFlight.Text = "";
            txtRemarksFlight.Text = "";

            //ModalPopupExtenderFlights.Show();
        }

        protected void VerificaFlight()
        {
            try
            {
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileFlightsDAL ffd = new FileFlightsDAL();
                FileTransfersDAL fttd = new FileTransfersDAL();
                FileServExtraDAL fsed = new FileServExtraDAL();

                File_ServExtra fseant = new File_ServExtra();
                File_Tarifas ftant = new File_Tarifas();
                File_Transfers fttant = new File_Transfers();

                if (!ViewState["IdFileServicoFlight"].Equals(""))
                {
                    fttant = fttd.ObterPorId(Convert.ToInt32(ViewState["IdFileServicoFlight"]));

                    if (fttant.Trf_Tours.Equals("TRS"))
                    {
                        lblConfirmationNumber.Visible = false;
                        txtConfirmationNumber.Visible = false;
                    }
                    else
                    {
                        lblConfirmationNumber.Visible = true;
                        txtConfirmationNumber.Visible = true;
                    }


                    if (fttant.Flights_id != null)
                    {
                        File_Flights ff = ffd.ObterPorId(Convert.ToInt32(fttant.Flights_id));

                        if (ff.Cidade_id == 0)
                        {
                            SelectCidade(1);
                            txtCidadeFlights.Text = ff.Cidade_iata;
                        }
                        else
                        {
                            SelectCidade(0);
                            ddlCidadeFlights.SelectedValue = ff.Cidade_id.ToString();
                        }

                        if (ff.Flights_DataFrom == true)
                        {
                            rdoInOutFlights.SelectedValue = "In";
                        }
                        else
                        {
                            rdoInOutFlights.SelectedValue = "To";
                        }

                        if (ff.Flights_ConfirmationNbr != null)
                        {
                            txtConfirmationNumber.Text = ff.Flights_ConfirmationNbr;
                        }

                        txtFlight.Text = ff.Flights_nome;
                        txtHoraFlight.Text = ff.Flights_hora;
                        txtPickUpFlight.Text = ff.Flights_pickUp;
                        txtDropOffFlight.Text = ff.Flights_dropOff;
                        txtRemarksFlight.Text = ff.Flights_remarks;



                        btnSalvarFlight.Text = "Atualizar";
                    }
                    else
                    {
                        LimpaTelaFlight();
                    }
                }
                else if (!ViewState["IdFileHotelFlight"].Equals(""))
                {
                    ftant = ftd.ObterPorId(Convert.ToInt32(ViewState["IdFileHotelFlight"]));

                    if (ftant.Flights_id != null)
                    {
                        File_Flights ff = ffd.ObterPorId(Convert.ToInt32(ftant.Flights_id));

                        if (ff.Cidade_id == 0)
                        {
                            SelectCidade(1);
                            txtCidadeFlights.Text = ff.Cidade_iata;
                        }
                        else
                        {
                            SelectCidade(0);
                            ddlCidadeFlights.SelectedValue = ff.Cidade_id.ToString();
                        }

                        if (ff.Flights_DataFrom == true)
                        {
                            rdoInOutFlights.SelectedValue = "In";
                        }
                        else
                        {
                            rdoInOutFlights.SelectedValue = "To";
                        }
                        if (ff.Flights_ConfirmationNbr != null)
                        {
                            txtConfirmationNumber.Text = ff.Flights_ConfirmationNbr;
                        }

                        txtFlight.Text = ff.Flights_nome;
                        txtHoraFlight.Text = ff.Flights_hora;
                        txtPickUpFlight.Text = ff.Flights_pickUp;
                        txtDropOffFlight.Text = ff.Flights_dropOff;
                        txtRemarksFlight.Text = ff.Flights_remarks;

                        btnSalvarFlight.Text = "Atualizar";
                    }
                    else
                    {
                        LimpaTelaFlight();
                    }
                }
                else if (!ViewState["IdFileServExtraFlight"].Equals(""))
                {
                    fseant = fsed.ObterPorId(Convert.ToInt32(ViewState["IdFileServExtraFlight"]));

                    if (fseant.Flights_id != null)
                    {
                        File_Flights ff = ffd.ObterPorId(Convert.ToInt32(fseant.Flights_id));

                        if (ff.Cidade_id == 0)
                        {
                            SelectCidade(1);
                            txtCidadeFlights.Text = ff.Cidade_iata;
                        }
                        else
                        {
                            SelectCidade(0);
                            ddlCidadeFlights.SelectedValue = ff.Cidade_id.ToString();
                        }

                        if (ff.Flights_DataFrom == true)
                        {
                            rdoInOutFlights.SelectedValue = "In";
                        }
                        else
                        {
                            rdoInOutFlights.SelectedValue = "To";
                        }
                        if (ff.Flights_ConfirmationNbr != null)
                        {
                            txtConfirmationNumber.Text = ff.Flights_ConfirmationNbr;
                        }

                        txtFlight.Text = ff.Flights_nome;
                        txtHoraFlight.Text = ff.Flights_hora;
                        txtPickUpFlight.Text = ff.Flights_pickUp;
                        txtDropOffFlight.Text = ff.Flights_dropOff;
                        txtRemarksFlight.Text = ff.Flights_remarks;

                        btnSalvarFlight.Text = "Atualizar";
                    }
                    else
                    {
                        LimpaTelaFlight();
                    }
                }

                ModalPopupExtenderFlights.Show();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void VerificaFlightNew()
        {
            try
            {

                FileFlightsDAL ffd = new FileFlightsDAL();
                QuoteTarifasDAL ftd = new QuoteTarifasDAL();
                QuoteTransDAL fttd = new QuoteTransDAL();
                QuoteServExtDAL fsed = new QuoteServExtDAL();

                Quote_ServExtra fseant = new Quote_ServExtra();
                Quote_Tarifas ftant = new Quote_Tarifas();
                Quote_Transf fttant = new Quote_Transf();

                if (!ViewState["IdFileServicoFlight"].Equals(""))
                {
                    fttant = fttd.ObterPorId(Convert.ToInt32(ViewState["IdFileServicoFlight"]));

                    if (fttant.Trf_Tours.Equals("TRS"))
                    {
                        lblConfirmationNumber.Visible = false;
                        txtConfirmationNumber.Visible = false;
                    }
                    else
                    {
                        lblConfirmationNumber.Visible = true;
                        txtConfirmationNumber.Visible = true;
                    }


                    if (fttant.Flights_id != null)
                    {
                        File_Flights ff = ffd.ObterPorId(Convert.ToInt32(fttant.Flights_id));

                        if (ff.Cidade_id == 0)
                        {
                            SelectCidade(1);
                            txtCidadeFlights.Text = ff.Cidade_iata;
                        }
                        else
                        {
                            SelectCidade(0);
                            ddlCidadeFlights.SelectedValue = ff.Cidade_id.ToString();
                        }

                        if (ff.Flights_DataFrom == true)
                        {
                            rdoInOutFlights.SelectedValue = "In";
                        }
                        else
                        {
                            rdoInOutFlights.SelectedValue = "To";
                        }

                        if (ff.Flights_ConfirmationNbr != null)
                        {
                            txtConfirmationNumber.Text = ff.Flights_ConfirmationNbr;
                        }

                        txtFlight.Text = ff.Flights_nome;
                        txtHoraFlight.Text = ff.Flights_hora;
                        txtPickUpFlight.Text = ff.Flights_pickUp;
                        txtDropOffFlight.Text = ff.Flights_dropOff;
                        txtRemarksFlight.Text = ff.Flights_remarks;



                        btnSalvarFlight.Text = "Atualizar";
                    }
                    else
                    {
                        LimpaTelaFlight();
                    }
                }
                else if (!ViewState["IdFileHotelFlight"].Equals(""))
                {
                    ftant = ftd.ObterPorId(Convert.ToInt32(ViewState["IdFileHotelFlight"]));

                    if (ftant.Flights_id != null)
                    {
                        File_Flights ff = ffd.ObterPorId(Convert.ToInt32(ftant.Flights_id));

                        if (ff.Cidade_id == 0)
                        {
                            SelectCidade(1);
                            txtCidadeFlights.Text = ff.Cidade_iata;
                        }
                        else
                        {
                            SelectCidade(0);
                            ddlCidadeFlights.SelectedValue = ff.Cidade_id.ToString();
                        }

                        if (ff.Flights_DataFrom == true)
                        {
                            rdoInOutFlights.SelectedValue = "In";
                        }
                        else
                        {
                            rdoInOutFlights.SelectedValue = "To";
                        }
                        if (ff.Flights_ConfirmationNbr != null)
                        {
                            txtConfirmationNumber.Text = ff.Flights_ConfirmationNbr;
                        }

                        txtFlight.Text = ff.Flights_nome;
                        txtHoraFlight.Text = ff.Flights_hora;
                        txtPickUpFlight.Text = ff.Flights_pickUp;
                        txtDropOffFlight.Text = ff.Flights_dropOff;
                        txtRemarksFlight.Text = ff.Flights_remarks;

                        btnSalvarFlight.Text = "Atualizar";
                    }
                    else
                    {
                        LimpaTelaFlight();
                    }
                }
                else if (!ViewState["IdFileServExtraFlight"].Equals(""))
                {
                    fseant = fsed.ObterPorId(Convert.ToInt32(ViewState["IdFileServExtraFlight"]));

                    if (fseant.Flights_id != null)
                    {
                        File_Flights ff = ffd.ObterPorId(Convert.ToInt32(fseant.Flights_id));

                        if (ff.Cidade_id == 0)
                        {
                            SelectCidade(1);
                            txtCidadeFlights.Text = ff.Cidade_iata;
                        }
                        else
                        {
                            SelectCidade(0);
                            ddlCidadeFlights.SelectedValue = ff.Cidade_id.ToString();
                        }

                        if (ff.Flights_DataFrom == true)
                        {
                            rdoInOutFlights.SelectedValue = "In";
                        }
                        else
                        {
                            rdoInOutFlights.SelectedValue = "To";
                        }
                        if (ff.Flights_ConfirmationNbr != null)
                        {
                            txtConfirmationNumber.Text = ff.Flights_ConfirmationNbr;
                        }

                        txtFlight.Text = ff.Flights_nome;
                        txtHoraFlight.Text = ff.Flights_hora;
                        txtPickUpFlight.Text = ff.Flights_pickUp;
                        txtDropOffFlight.Text = ff.Flights_dropOff;
                        txtRemarksFlight.Text = ff.Flights_remarks;

                        btnSalvarFlight.Text = "Atualizar";
                    }
                    else
                    {
                        LimpaTelaFlight();
                    }
                }

                ModalPopupExtenderFlights.Show();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnSalvarFlight_Click(object sender, EventArgs e)
        {
            try
            {
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileFlightsDAL ffd = new FileFlightsDAL();
                FileTransfersDAL fttd = new FileTransfersDAL();
                FileServExtraDAL fsed = new FileServExtraDAL();

                File_ServExtra fsant = new File_ServExtra();
                File_Tarifas ftant = new File_Tarifas();
                File_Transfers fttant = new File_Transfers();
                File_Flights ff = new File_Flights();

                if (!ViewState["IdFileServicoFlight"].Equals(""))
                {
                    fttant = fttd.ObterPorId(Convert.ToInt32(ViewState["IdFileServicoFlight"]));

                    if (fttant.Flights_id == null)
                    {

                        if (rdoInOutFlights.SelectedValue.Equals("In"))
                        {
                            ff.Flights_DataFrom = true;
                        }
                        else
                        {
                            ff.Flights_DataTo = true;
                        }

                        ff.Flights_nome = txtFlight.Text;
                        ff.Flights_hora = txtHoraFlight.Text;
                        ff.Flights_pickUp = txtPickUpFlight.Text;
                        ff.Flights_dropOff = txtDropOffFlight.Text;
                        ff.Flights_remarks = txtRemarksFlight.Text;

                        if (ddlCidadeFlights.SelectedValue.Equals("0"))
                        {
                            ff.Cidade_iata = txtCidadeFlights.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }
                        else
                        {
                            ff.Cidade_iata = ddlCidadeFlights.SelectedItem.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }

                        ffd.Salvar(ff);

                        File_Transfers ft = new File_Transfers();

                        ft.File_Transf_id = Convert.ToInt32(ViewState["IdFileServicoFlight"]);
                        ft.Flights_id = ff.Flights_id;

                        fttd.AtualizarFlight(ft);

                        PopularGridListCarrinhoTransfers(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                        MostrarMsg("Registro cadastrado com sucesso.");
                    }
                    else
                    {

                        ff.Flights_id = Convert.ToInt32(fttant.Flights_id);

                        if (ddlCidadeFlights.SelectedValue.Equals("0"))
                        {
                            ff.Cidade_iata = txtCidadeFlights.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }
                        else
                        {
                            ff.Cidade_iata = ddlCidadeFlights.SelectedItem.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }

                        ff.Flights_nome = txtFlight.Text;
                        ff.Flights_hora = txtHoraFlight.Text;
                        ff.Flights_pickUp = txtPickUpFlight.Text;
                        ff.Flights_dropOff = txtDropOffFlight.Text;
                        ff.Flights_remarks = txtRemarksFlight.Text;

                        ffd.Atualizar(ff);

                        MostrarMsg("Registro atualizado com sucesso.");
                    }
                }
                else if (!ViewState["IdFileHotelFlight"].Equals(""))
                {
                    ftant = ftd.ObterPorId(Convert.ToInt32(ViewState["IdFileHotelFlight"]));

                    if (ftant.Flights_id == null)
                    {

                        if (rdoInOutFlights.SelectedValue.Equals("In"))
                        {
                            ff.Flights_DataFrom = true;
                        }
                        else
                        {
                            ff.Flights_DataTo = true;
                        }

                        ff.Flights_nome = txtFlight.Text;
                        ff.Flights_hora = txtHoraFlight.Text;
                        ff.Flights_pickUp = txtPickUpFlight.Text;
                        ff.Flights_dropOff = txtDropOffFlight.Text;
                        ff.Flights_remarks = txtRemarksFlight.Text;

                        if (ddlCidadeFlights.SelectedValue.Equals("0"))
                        {
                            ff.Cidade_iata = txtCidadeFlights.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }
                        else
                        {
                            ff.Cidade_iata = ddlCidadeFlights.SelectedItem.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }

                        ffd.Salvar(ff);



                        File_Tarifas ft = new File_Tarifas();

                        ft.File_Tarifas_id = Convert.ToInt32(ViewState["IdFileHotelFlight"]);
                        ft.Flights_id = ff.Flights_id;

                        ftd.AtualizarFlight(ft);

                        PopularGridListCarrinho(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                        MostrarMsg("Registro cadastrado com sucesso.");
                    }
                    else
                    {

                        ff.Flights_id = Convert.ToInt32(ftant.Flights_id);

                        if (ddlCidadeFlights.SelectedValue.Equals("0"))
                        {
                            ff.Cidade_iata = txtCidadeFlights.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }
                        else
                        {
                            ff.Cidade_iata = ddlCidadeFlights.SelectedItem.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }

                        ff.Flights_nome = txtFlight.Text;
                        ff.Flights_hora = txtHoraFlight.Text;
                        ff.Flights_pickUp = txtPickUpFlight.Text;
                        ff.Flights_dropOff = txtDropOffFlight.Text;
                        ff.Flights_remarks = txtRemarksFlight.Text;

                        ffd.Atualizar(ff);

                        MostrarMsg("Registro atualizado com sucesso.");
                    }
                }
                else if (!ViewState["IdFileServExtraFlight"].Equals(""))
                {

                    fsant = fsed.ObterPorId(Convert.ToInt32(ViewState["IdFileServExtraFlight"]));

                    if (fsant.Flights_id == null)
                    {

                        if (rdoInOutFlights.SelectedValue.Equals("In"))
                        {
                            ff.Flights_DataFrom = true;
                        }
                        else
                        {
                            ff.Flights_DataTo = true;
                        }

                        ff.Flights_nome = txtFlight.Text;
                        ff.Flights_hora = txtHoraFlight.Text;
                        ff.Flights_pickUp = txtPickUpFlight.Text;
                        ff.Flights_dropOff = txtDropOffFlight.Text;
                        ff.Flights_remarks = txtRemarksFlight.Text;

                        if (ddlCidadeFlights.SelectedValue.Equals("0"))
                        {
                            ff.Cidade_iata = txtCidadeFlights.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }
                        else
                        {
                            ff.Cidade_iata = ddlCidadeFlights.SelectedItem.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }

                        ffd.Salvar(ff);



                        File_ServExtra ft = new File_ServExtra();

                        ft.File_ServExtra_id = Convert.ToInt32(ViewState["IdFileServExtraFlight"]);
                        ft.Flights_id = ff.Flights_id;

                        fsed.AtualizarFlight(ft);

                        PopularGridListCarrinhoExtras(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                        MostrarMsg("Registro cadastrado com sucesso.");
                    }
                    else
                    {

                        ff.Flights_id = Convert.ToInt32(fsant.Flights_id);

                        if (ddlCidadeFlights.SelectedValue.Equals("0"))
                        {
                            ff.Cidade_iata = txtCidadeFlights.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }
                        else
                        {
                            ff.Cidade_iata = ddlCidadeFlights.SelectedItem.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }

                        ff.Flights_nome = txtFlight.Text;
                        ff.Flights_hora = txtHoraFlight.Text;
                        ff.Flights_pickUp = txtPickUpFlight.Text;
                        ff.Flights_dropOff = txtDropOffFlight.Text;
                        ff.Flights_remarks = txtRemarksFlight.Text;

                        ffd.Atualizar(ff);

                        MostrarMsg("Registro atualizado com sucesso.");
                    }

                }

                //ModalPopupExtenderFlights.Show();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnSalvarFlightNew_Click(object sender, EventArgs e)
        {
            try
            {
                QuoteTarifasDAL ftd = new QuoteTarifasDAL();
                FileFlightsDAL ffd = new FileFlightsDAL();
                QuoteTransDAL fttd = new QuoteTransDAL();
                QuoteServExtDAL fsed = new QuoteServExtDAL();

                Quote_ServExtra fsant = new Quote_ServExtra();
                Quote_Tarifas ftant = new Quote_Tarifas();
                Quote_Transf fttant = new Quote_Transf();
                File_Flights ff = new File_Flights();

                if (!ViewState["IdFileServicoFlight"].Equals(""))
                {
                    fttant = fttd.ObterPorId(Convert.ToInt32(ViewState["IdFileServicoFlight"]));

                    if (fttant.Flights_id == null)
                    {

                        if (rdoInOutFlights.SelectedValue.Equals("In"))
                        {
                            ff.Flights_DataFrom = true;
                        }
                        else
                        {
                            ff.Flights_DataTo = true;
                        }

                        ff.Flights_nome = txtFlight.Text;
                        ff.Flights_hora = txtHoraFlight.Text;
                        ff.Flights_pickUp = txtPickUpFlight.Text;
                        ff.Flights_dropOff = txtDropOffFlight.Text;
                        ff.Flights_remarks = txtRemarksFlight.Text;

                        if (ddlCidadeFlights.SelectedValue.Equals("0"))
                        {
                            ff.Cidade_iata = txtCidadeFlights.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }
                        else
                        {
                            ff.Cidade_iata = ddlCidadeFlights.SelectedItem.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }

                        ffd.Salvar(ff);

                        Quote_Transf ft = new Quote_Transf();

                        ft.Quote_Transf_id = Convert.ToInt32(ViewState["IdFileServicoFlight"]);
                        ft.Flights_id = ff.Flights_id;

                        fttd.AtualizarFlight(ft);

                        PopularGridListCarrinhoTransfers(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                        MostrarMsg("Registro cadastrado com sucesso.");
                    }
                    else
                    {

                        ff.Flights_id = Convert.ToInt32(fttant.Flights_id);

                        if (ddlCidadeFlights.SelectedValue.Equals("0"))
                        {
                            ff.Cidade_iata = txtCidadeFlights.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }
                        else
                        {
                            ff.Cidade_iata = ddlCidadeFlights.SelectedItem.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }

                        ff.Flights_nome = txtFlight.Text;
                        ff.Flights_hora = txtHoraFlight.Text;
                        ff.Flights_pickUp = txtPickUpFlight.Text;
                        ff.Flights_dropOff = txtDropOffFlight.Text;
                        ff.Flights_remarks = txtRemarksFlight.Text;

                        ffd.Atualizar(ff);

                        MostrarMsg("Registro atualizado com sucesso.");
                    }
                }
                else if (!ViewState["IdFileHotelFlight"].Equals(""))
                {
                    ftant = ftd.ObterPorId(Convert.ToInt32(ViewState["IdFileHotelFlight"]));

                    if (ftant.Flights_id == null)
                    {

                        if (rdoInOutFlights.SelectedValue.Equals("In"))
                        {
                            ff.Flights_DataFrom = true;
                        }
                        else
                        {
                            ff.Flights_DataTo = true;
                        }

                        ff.Flights_nome = txtFlight.Text;
                        ff.Flights_hora = txtHoraFlight.Text;
                        ff.Flights_pickUp = txtPickUpFlight.Text;
                        ff.Flights_dropOff = txtDropOffFlight.Text;
                        ff.Flights_remarks = txtRemarksFlight.Text;

                        if (ddlCidadeFlights.SelectedValue.Equals("0"))
                        {
                            ff.Cidade_iata = txtCidadeFlights.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }
                        else
                        {
                            ff.Cidade_iata = ddlCidadeFlights.SelectedItem.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }

                        ffd.Salvar(ff);

                        Quote_Tarifas ft = new Quote_Tarifas();

                        ft.Quote_Tarifas_id = Convert.ToInt32(ViewState["IdFileHotelFlight"]);
                        ft.Flights_id = ff.Flights_id;

                        ftd.AtualizarFlight(ft);

                        PopularGridListCarrinho(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                        MostrarMsg("Registro cadastrado com sucesso.");
                    }
                    else
                    {

                        ff.Flights_id = Convert.ToInt32(ftant.Flights_id);

                        if (ddlCidadeFlights.SelectedValue.Equals("0"))
                        {
                            ff.Cidade_iata = txtCidadeFlights.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }
                        else
                        {
                            ff.Cidade_iata = ddlCidadeFlights.SelectedItem.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }

                        ff.Flights_nome = txtFlight.Text;
                        ff.Flights_hora = txtHoraFlight.Text;
                        ff.Flights_pickUp = txtPickUpFlight.Text;
                        ff.Flights_dropOff = txtDropOffFlight.Text;
                        ff.Flights_remarks = txtRemarksFlight.Text;

                        ffd.Atualizar(ff);

                        MostrarMsg("Registro atualizado com sucesso.");
                    }
                }
                else if (!ViewState["IdFileServExtraFlight"].Equals(""))
                {

                    fsant = fsed.ObterPorId(Convert.ToInt32(ViewState["IdFileServExtraFlight"]));

                    if (fsant.Flights_id == null)
                    {

                        if (rdoInOutFlights.SelectedValue.Equals("In"))
                        {
                            ff.Flights_DataFrom = true;
                        }
                        else
                        {
                            ff.Flights_DataTo = true;
                        }

                        ff.Flights_nome = txtFlight.Text;
                        ff.Flights_hora = txtHoraFlight.Text;
                        ff.Flights_pickUp = txtPickUpFlight.Text;
                        ff.Flights_dropOff = txtDropOffFlight.Text;
                        ff.Flights_remarks = txtRemarksFlight.Text;

                        if (ddlCidadeFlights.SelectedValue.Equals("0"))
                        {
                            ff.Cidade_iata = txtCidadeFlights.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }
                        else
                        {
                            ff.Cidade_iata = ddlCidadeFlights.SelectedItem.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }

                        ffd.Salvar(ff);

                        Quote_ServExtra ft = new Quote_ServExtra();

                        ft.Quote_ServExtra_id = Convert.ToInt32(ViewState["IdFileServExtraFlight"]);
                        ft.Flights_id = ff.Flights_id;

                        fsed.AtualizarFlight(ft);

                        PopularGridListCarrinhoExtras(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                        MostrarMsg("Registro cadastrado com sucesso.");
                    }
                    else
                    {

                        ff.Flights_id = Convert.ToInt32(fsant.Flights_id);

                        if (ddlCidadeFlights.SelectedValue.Equals("0"))
                        {
                            ff.Cidade_iata = txtCidadeFlights.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }
                        else
                        {
                            ff.Cidade_iata = ddlCidadeFlights.SelectedItem.Text;
                            ff.Cidade_id = Convert.ToInt32(ddlCidadeFlights.SelectedValue);
                        }

                        ff.Flights_nome = txtFlight.Text;
                        ff.Flights_hora = txtHoraFlight.Text;
                        ff.Flights_pickUp = txtPickUpFlight.Text;
                        ff.Flights_dropOff = txtDropOffFlight.Text;
                        ff.Flights_remarks = txtRemarksFlight.Text;

                        ffd.Atualizar(ff);

                        MostrarMsg("Registro atualizado com sucesso.");
                    }

                }

                //ModalPopupExtenderFlights.Show();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        #endregion

        #region Regras Paxs

        protected void LimpaTelaPaxs()
        {
            txtPayingPaxPop.Text = "";
            txtSupplierPayingPaxPop.Text = "";
        }

        protected void VerificaPaxs()
        {
            try
            {
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileTransfersDAL fttd = new FileTransfersDAL();
                FileServExtraDAL fsed = new FileServExtraDAL();

                File_ServExtra fse = new File_ServExtra();
                File_Transfers ftt = new File_Transfers();
                File_Tarifas ft = new File_Tarifas();


                if (!ViewState["IdFilePaxsHoteis"].Equals(""))
                {
                    if (ftd.ObterPorId(Convert.ToInt32(ViewState["IdFilePaxsHoteis"])).Paying_Pax != null)
                    {
                        ft = ftd.ObterPorId(Convert.ToInt32(ViewState["IdFilePaxsHoteis"]));
                        txtPayingPaxPop.Text = ft.Paying_Pax.ToString();
                        txtSupplierPayingPaxPop.Text = ft.Supp_Paying_Pax.ToString();
                        txtPaxsPop.Text = ft.Paxs.ToString();
                    }
                    else
                    {
                        LimpaTelaPaxs();
                    }
                }
                else if (!ViewState["IdFilePaxsServicos"].Equals(""))
                {
                    if (fttd.ObterPorId(Convert.ToInt32(ViewState["IdFilePaxsServicos"])).Paying_Pax != null)
                    {
                        ftt = fttd.ObterPorId(Convert.ToInt32(ViewState["IdFilePaxsServicos"]));
                        txtPayingPaxPop.Text = ftt.Paying_Pax.ToString();
                        txtSupplierPayingPaxPop.Text = ftt.Supp_Paying_Pax.ToString();
                        txtPaxsPop.Text = ftt.Paxs.ToString();
                    }
                    else
                    {
                        LimpaTelaPaxs();
                    }
                }
                else if (!ViewState["IdFilePaxsServExtras"].Equals(""))
                {
                    if (fsed.ObterPorId(Convert.ToInt32(ViewState["IdFilePaxsServExtras"])).Paying_Pax != null)
                    {
                        fse = fsed.ObterPorId(Convert.ToInt32(ViewState["IdFilePaxsServExtras"]));
                        txtPayingPaxPop.Text = fse.Paying_Pax.ToString();
                        txtSupplierPayingPaxPop.Text = fse.Supp_Paying_Pax.ToString();
                        txtPaxsPop.Text = fse.Paxs.ToString();
                    }
                    else
                    {
                        LimpaTelaPaxs();
                    }
                }


            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnSalvarPaxsPop_Click(object sender, EventArgs e)
        {
            try
            {
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileTransfersDAL fttd = new FileTransfersDAL();
                FileServExtraDAL fsed = new FileServExtraDAL();

                File_ServExtra fse = new File_ServExtra();
                File_Transfers ftt = new File_Transfers();
                File_Tarifas ft = new File_Tarifas();

                if (!ViewState["IdFilePaxsHoteis"].Equals(""))
                {
                    ft.File_Tarifas_id = Convert.ToInt32(ViewState["IdFilePaxsHoteis"]);
                    ft.Paying_Pax = Convert.ToInt32(txtPayingPaxPop.Text);
                    ft.Supp_Paying_Pax = Convert.ToInt32(txtSupplierPayingPaxPop.Text);
                    ft.Paxs = Convert.ToInt32(txtPaxsPop.Text);
                    ft.Qtd_Tarifas = Convert.ToInt32(txtPaxsPop.Text);

                    ftd.AtualizarPaxs(ft);

                    PopularGridListCarrinho(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                }
                else if (!ViewState["IdFilePaxsServicos"].Equals(""))
                {
                    ftt.File_Transf_id = Convert.ToInt32(ViewState["IdFilePaxsServicos"]);
                    ftt.Paying_Pax = Convert.ToInt32(txtPayingPaxPop.Text);
                    ftt.Supp_Paying_Pax = Convert.ToInt32(txtSupplierPayingPaxPop.Text);
                    ftt.Paxs = Convert.ToInt32(txtPaxsPop.Text);
                    ftt.Qtd_Transf = Convert.ToInt32(txtPaxsPop.Text);

                    fttd.AtualizarPaxs(ftt);

                    PopularGridListCarrinhoTransfers(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                }
                else if (!ViewState["IdFilePaxsServExtras"].Equals(""))
                {
                    fse.File_ServExtra_id = Convert.ToInt32(ViewState["IdFilePaxsServExtras"]);
                    fse.Paying_Pax = Convert.ToInt32(txtPayingPaxPop.Text);
                    fse.Supp_Paying_Pax = Convert.ToInt32(txtSupplierPayingPaxPop.Text);
                    fse.Paxs = Convert.ToInt32(txtPaxsPop.Text);
                    fse.Qtd_ServExtr = Convert.ToInt32(txtPaxsPop.Text);

                    fsed.AtualizarPaxs(fse);

                    PopularGridListCarrinhoExtras(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                }

                //ModalPopupExtenderPaxs.Show();

                MostrarMsg("Registro cadastrado com sucesso.");
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        #endregion

        #region Regras Quote

        protected void btnPrintQuote_Click(object sender, EventArgs e)
        {
            try
            {
                string script = "";
                script = script + "window.open('/Externo4Star/QuoteGeralNew.aspx?idQ=" + ViewState["IdQuotGrupo"] + "','', " + "'status=1, scrollbars=yes, width=820, height=620, top=0, left=0');";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Quote", script, true);

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void imgSetaCima_Command(object sender, CommandEventArgs e)
        {
            try
            {
                FileTarifasDAL ftdal = new FileTarifasDAL();
                FileTransfersDAL ftrdal = new FileTransfersDAL();
                FileServExtraDAL fsexdal = new FileServExtraDAL();

                string[] pars = e.CommandArgument.ToString().Split(',');

                File_Tarifas ft, ftu = new File_Tarifas();
                File_Transfers ftr, ftru = new File_Transfers();
                File_ServExtra fext, fextu = new File_ServExtra(); ;

                int flag = 0;
                int ordem1 = 0, ordem2 = 0;
                int id1 = 0, id2 = 0;
                string data1 = "", data2 = "", type = "";

                foreach (GridViewRow item in GridBasesTarifas.Rows)
                {
                    HiddenField hdfOrdem = (HiddenField)item.FindControl("hdfOrdem");
                    Label lblFlag = (Label)item.FindControl("lblFlag");
                    Label lblIdRetorna = (Label)item.FindControl("lblIdRetorna");

                    flag = 0;

                    if (item.DataItemIndex == Convert.ToInt32(pars[3]))
                    {
                        switch (pars[1].ToString())
                        {
                            case "hotel":
                                ft = ftdal.ObterPorId(Convert.ToInt32(pars[0]));
                                ordem2 = (int)ft.Ordem;
                                data2 = ft.Data_From.ToString();
                                id2 = ft.File_Tarifas_id;
                                break;
                            case "servico":
                                ftr = ftrdal.ObterPorId(Convert.ToInt32(pars[0]));
                                ordem2 = (int)ftr.Ordem;
                                data2 = ftr.Data_From.ToString();
                                id2 = ftr.File_Transf_id;
                                break;
                            case "extra":
                                fext = fsexdal.ObterPorId(Convert.ToInt32(pars[0]));
                                ordem2 = (int)fext.Ordem;
                                data2 = fext.Data_From.ToString();
                                id2 = fext.File_ServExtra_id;
                                break;
                        }

                        flag = 1;
                    }

                    if (flag == 0)
                    {
                        switch (lblFlag.Text.ToString())
                        {
                            case "hotel":
                                ftu = ftdal.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                ordem1 = (int)ftu.Ordem;
                                data1 = ftu.Data_From.ToString();
                                id1 = ftu.File_Tarifas_id;
                                type = "hotel";
                                break;
                            case "servico":
                                ftru = ftrdal.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                ordem1 = (int)ftru.Ordem;
                                data1 = ftru.Data_From.ToString();
                                id1 = ftru.File_Transf_id;
                                type = "servico";
                                break;
                            case "extra":
                                fextu = fsexdal.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                ordem1 = (int)fextu.Ordem;
                                data1 = fextu.Data_From.ToString();
                                id1 = fextu.File_ServExtra_id;
                                type = "extra";
                                break;
                        }
                    }

                    if (data1.Equals(data2))
                    {
                        switch (pars[1].ToString())
                        {
                            case "hotel":
                                ft = new File_Tarifas();
                                ft.Ordem = ordem1;
                                ft.File_Tarifas_id = id2;
                                ftdal.AtualizarOrdem(ft);
                                break;
                            case "servico":
                                ftr = new File_Transfers();
                                ftr.Ordem = ordem1;
                                ftr.File_Transf_id = id2;
                                ftrdal.AtualizarOrdem(ftr);
                                break;
                            case "extra":
                                fext = new File_ServExtra();
                                fext.Ordem = ordem1;
                                fext.File_ServExtra_id = id2;
                                fsexdal.AtualizarOrdem(fext);
                                break;
                        }

                        switch (type)
                        {
                            case "hotel":
                                ftu = new File_Tarifas();
                                ftu.Ordem = ordem2;
                                ftu.File_Tarifas_id = id1;
                                ftdal.AtualizarOrdem(ftu);
                                break;
                            case "servico":
                                ftru = new File_Transfers();
                                ftru.Ordem = ordem2;
                                ftru.File_Transf_id = id1;
                                ftrdal.AtualizarOrdem(ftru);
                                break;
                            case "extra":
                                fextu = new File_ServExtra();
                                fextu.Ordem = ordem2;
                                fextu.File_ServExtra_id = id1;
                                fsexdal.AtualizarOrdem(fextu);
                                break;
                        }

                        break;
                    }



                }

                PopulaNewQuote(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToInt32(ViewState["QuoteAtiva"]));
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void imgSetaBaixo_Command(object sender, CommandEventArgs e)
        {
            try
            {
                FileTarifasDAL ftdal = new FileTarifasDAL();
                FileTransfersDAL ftrdal = new FileTransfersDAL();
                FileServExtraDAL fsexdal = new FileServExtraDAL();

                string[] pars = e.CommandArgument.ToString().Split(',');

                File_Tarifas ft, ftu = new File_Tarifas();
                File_Transfers ftr, ftru = new File_Transfers();
                File_ServExtra fext, fextu = new File_ServExtra(); ;

                int flag = 0;
                int ordem1 = 0, ordem2 = 0;
                int id1 = 0, id2 = 0;
                string data1 = "1", data2 = "2", type = "";

                foreach (GridViewRow item in GridBasesTarifas.Rows)
                {
                    HiddenField hdfOrdem = (HiddenField)item.FindControl("hdfOrdem");
                    Label lblFlag = (Label)item.FindControl("lblFlag");
                    Label lblIdRetorna = (Label)item.FindControl("lblIdRetorna");

                    flag = 0;

                    if (item.DataItemIndex == Convert.ToInt32(pars[3]))
                    {
                        switch (pars[1].ToString())
                        {
                            case "hotel":
                                ft = ftdal.ObterPorId(Convert.ToInt32(pars[0]));
                                ordem2 = (int)ft.Ordem;
                                data2 = ft.Data_From.ToString();
                                id2 = ft.File_Tarifas_id;
                                break;
                            case "servico":
                                ftr = ftrdal.ObterPorId(Convert.ToInt32(pars[0]));
                                ordem2 = (int)ftr.Ordem;
                                data2 = ftr.Data_From.ToString();
                                id2 = ftr.File_Transf_id;
                                break;
                            case "extra":
                                fext = fsexdal.ObterPorId(Convert.ToInt32(pars[0]));
                                ordem2 = (int)fext.Ordem;
                                data2 = fext.Data_From.ToString();
                                id2 = fext.File_ServExtra_id;
                                break;
                        }

                        flag = 1;
                    }

                    if (item.DataItemIndex > Convert.ToInt32(pars[3]))
                    {
                        if (flag == 0)
                        {
                            switch (lblFlag.Text.ToString())
                            {
                                case "hotel":
                                    ftu = ftdal.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                    ordem1 = (int)ftu.Ordem;
                                    data1 = ftu.Data_From.ToString();
                                    id1 = ftu.File_Tarifas_id;
                                    type = "hotel";
                                    break;
                                case "servico":
                                    ftru = ftrdal.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                    ordem1 = (int)ftru.Ordem;
                                    data1 = ftru.Data_From.ToString();
                                    id1 = ftru.File_Transf_id;
                                    type = "servico";
                                    break;
                                case "extra":
                                    fextu = fsexdal.ObterPorId(Convert.ToInt32(lblIdRetorna.Text));
                                    ordem1 = (int)fextu.Ordem;
                                    data1 = fextu.Data_From.ToString();
                                    id1 = fextu.File_ServExtra_id;
                                    type = "extra";
                                    break;
                            }
                        }
                    }

                    if (data1.Equals(data2))
                    {
                        switch (pars[1].ToString())
                        {
                            case "hotel":
                                ft = new File_Tarifas();
                                ft.Ordem = ordem1;
                                ft.File_Tarifas_id = id2;
                                ftdal.AtualizarOrdem(ft);
                                break;
                            case "servico":
                                ftr = new File_Transfers();
                                ftr.Ordem = ordem1;
                                ftr.File_Transf_id = id2;
                                ftrdal.AtualizarOrdem(ftr);
                                break;
                            case "extra":
                                fext = new File_ServExtra();
                                fext.Ordem = ordem1;
                                fext.File_ServExtra_id = id2;
                                fsexdal.AtualizarOrdem(fext);
                                break;
                        }

                        switch (type)
                        {
                            case "hotel":
                                ftu = new File_Tarifas();
                                ftu.Ordem = ordem2;
                                ftu.File_Tarifas_id = id1;
                                ftdal.AtualizarOrdem(ftu);
                                break;
                            case "servico":
                                ftru = new File_Transfers();
                                ftru.Ordem = ordem2;
                                ftru.File_Transf_id = id1;
                                ftrdal.AtualizarOrdem(ftru);
                                break;
                            case "extra":
                                fextu = new File_ServExtra();
                                fextu.Ordem = ordem2;
                                fextu.File_ServExtra_id = id1;
                                fsexdal.AtualizarOrdem(fextu);
                                break;
                        }

                        break;
                    }



                }

                PopulaNewQuote(Convert.ToInt32(ViewState["IdQuotGrupo"]), Convert.ToInt32(ViewState["QuoteAtiva"]));
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        #endregion

        #region Copiar File

        protected void btnCopiarFile_Click(object sender, EventArgs e)
        {
            lblFilePCopiar.Text = txtQuoteNumber.Text;

            ModalPopupExtenderCopiarFile.Show();
        }

        protected void btnCopiarFileGeral_Click(object sender, EventArgs e)
        {
            try
            {

                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                QuotationDAL qd = new QuotationDAL();
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();


                Quotation q;

                if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                {
                    q = new Quotation();
                    q.Quotation_Code = DateTime.Now.ToString("ddMMM");

                    qd.Salvar(q);

                    q.Quotation_Id = q.Quotation_Id;
                    q.Quotation_Code = q.Quotation_Code + q.Quotation_Id;

                    qd.Atualizar(q);
                }
                else
                {
                    q = new Quotation();
                    q.Quotation_Code = "";

                    qd.Salvar(q);

                    q.Quotation_Id = q.Quotation_Id;
                    q.Quotation_Code = q.Quotation_Id.ToString();

                    qd.Atualizar(q);
                }

                string NovoFile = q.Quotation_Code;
                int QuotId = q.Quotation_Id;

                int AntigoFileId = fcd.RetornaFile(txtQuoteNumber.Text);
                string AntgQuote = qd.ObterPorCode(txtQuoteNumber.Text).Quotation_Code;
                int AntigoQuotId = fcd.RetornaQuote(AntigoFileId);
                int AntigoQuotGrpId = qgd.ObterPorIdQuotation(AntigoQuotId).Quotation_Grupo_Id;


                Quotation_Grupo qgrupo = qgd.ObterPorId(AntigoQuotGrpId);

                Quotation_Grupo qgruponovo = new Quotation_Grupo();

                qgruponovo.Pax_Group_Name = qgrupo.Pax_Group_Name;
                qgruponovo.dataIN = qgrupo.dataIN;
                qgruponovo.dateOut = qgrupo.dateOut;
                qgruponovo.dataQuote = qgrupo.dataQuote;
                qgruponovo.Cliente_id = qgrupo.Cliente_id;
                qgruponovo.S_mercado_tipo_tarifa_id = qgrupo.S_mercado_tipo_tarifa_id;
                qgruponovo.FLinguagem_id = qgrupo.FLinguagem_id;
                qgruponovo.Moeda_id = qgrupo.Moeda_id;
                qgruponovo.Quotation_status_id = qgrupo.Quotation_status_id;
                qgruponovo.US_id = qgrupo.US_id;
                qgruponovo.Quotation_Id = QuotId;

                qgd.Salvar(qgruponovo);


                QuotationGrupoDAL qgdal = new QuotationGrupoDAL();

                int IdQGrupo = qgdal.ObterPorIdQuotation(QuotId).Quotation_Grupo_Id;


                File_Carrinho fc = new File_Carrinho();

                fc.Quotation_Grupo_Id = Convert.ToInt32(IdQGrupo);

                fcd.Salvar(fc);


                Quotation_Grupo_Qtd_Adult qgqa = new Quotation_Grupo_Qtd_Adult();
                qgqa.Quotation_Grupo_Id = qgruponovo.Quotation_Grupo_Id;
                qgqa.Qtd = Convert.ToInt32(ddlAdultos.SelectedValue);
                GrupoQtdAdultDAL gqad = new GrupoQtdAdultDAL();
                gqad.Salvar(qgqa);

                ddlNumPaxsTours.SelectedValue = ddlAdultos.SelectedValue;
                ddlNumPaxTransfers.SelectedValue = ddlAdultos.SelectedValue;

                Quotation_Grupo_Qtd_Chd qgqc = new Quotation_Grupo_Qtd_Chd();
                qgqc.Quotation_Grupo_Id = qgruponovo.Quotation_Grupo_Id;
                qgqc.Qtd = Convert.ToInt32(ddlChd.SelectedValue);
                GrupoQtdChdDAL gqcd = new GrupoQtdChdDAL();
                gqcd.Salvar(qgqc);


                Quotation_Grupo_Qtd_Baby qgqb = new Quotation_Grupo_Qtd_Baby();
                qgqb.Quotation_Grupo_Id = qgruponovo.Quotation_Grupo_Id;
                qgqb.Qtd = Convert.ToInt32(ddlInf.SelectedValue);
                GrupoQtdInfDAL gqbd = new GrupoQtdInfDAL();
                gqbd.Salvar(qgqb);

                PopulaGridGroup();


                //int FileId = fcd.RetornaFile(NovoFile);

                TarifaDAL td = new TarifaDAL();
                FileTarifasDAL fttdao = new FileTarifasDAL();
                SBasesDAL sbases = new SBasesDAL();

                DateTime first = Convert.ToDateTime(fttdao.ListarTodosOrderBy(AntigoFileId).First().Data_From);
                int dias = (Convert.ToDateTime(txtDataAddDias.Text) - first).Days;

                foreach (File_Tarifas item in fttdao.ListarTodos(AntigoFileId))
                {

                    File_Tarifas filetarifas = new File_Tarifas();

                    DateTime from = Convert.ToDateTime(item.Data_From).AddDays(dias);
                    DateTime to = Convert.ToDateTime(item.Data_To).AddDays(dias);

                    filetarifas.File_id = fc.File_id;
                    filetarifas.Flights_id = item.Flights_id;
                    filetarifas.Paxs = item.Paxs;
                    filetarifas.Paying_Pax = item.Paying_Pax;
                    filetarifas.Supp_Paying_Pax = item.Supp_Paying_Pax;
                    filetarifas.Data_From = from;
                    filetarifas.Data_To = to;
                    filetarifas.NumNoites = item.NumNoites;
                    filetarifas.Qtd_Tarifas = item.Qtd_Tarifas;
                    filetarifas.S_meal_nome = item.S_meal_nome;
                    filetarifas.S_meal_status = item.S_meal_status;
                    filetarifas.Meal = item.Meal;
                    filetarifas.S_meal_id = item.S_meal_id;

                    if (item.S_meal_nome != null)
                    {
                        filetarifas.markup = 0;
                        filetarifas.markupNet = 0;
                        filetarifas.desconto = 0;
                        filetarifas.descontoNet = 0;
                        filetarifas.S_merc_tarif_vendaNet = 0;
                        filetarifas.S_merc_tarif_venda = 0;
                        filetarifas.S_merc_tarif_total = 0;
                        filetarifas.S_merc_tarif_valor = 0;
                    }
                    else
                    {
                        string[] valores;

                        S_Mercado_Tarifa smt;

                        if (sbases.ObterPorIdSupplier(Convert.ToInt32(item.S_id)).Count > 0)
                        {
                            if (item.FdsFrom != null)
                            {
                                smt = td.ObterTarifaBase(Convert.ToInt32(item.S_id), from,
                                                                          to, item.Room, item.Categoria, item.NomePacote, item.FdsFrom, Convert.ToInt32(item.Paying_Pax));

                            }
                            else
                            {
                                smt = td.ObterTarifaBase(Convert.ToInt32(item.S_id), from,
                                                                          to, item.Room, item.Categoria, item.NomePacote, Convert.ToInt32(item.Paying_Pax));
                            }
                        }
                        else if (item.FdsFrom != null)
                        {
                            smt = td.ObterTarifa(Convert.ToInt32(item.S_id), from,
                                                                      to, item.Room, item.Categoria, item.NomePacote, item.FdsFrom);
                        }
                        else
                        {
                            smt = td.ObterTarifa(Convert.ToInt32(item.S_id), from,
                                                                      to, item.Room, item.Categoria, item.NomePacote);
                        }

                        if (smt != null)
                        {
                            filetarifas.markup = item.markup;
                            filetarifas.desconto = item.desconto;
                            filetarifas.markupNet = item.markupNet;
                            filetarifas.descontoNet = item.descontoNet;


                            decimal valor = 0;
                            decimal valorComCambio = 0;
                            decimal valorfinal = 0;

                            if (smt.S_Mercado_Periodo.Moeda_id != Convert.ToInt32(ddlMoeda.SelectedValue))
                            {
                                CambioDAL cambDal = new CambioDAL();

                                Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(smt.S_Mercado_Periodo.Moeda_id), Convert.ToInt32(ddlMoeda.SelectedValue));

                                if (smt.S_merc_tarif_porApartamento == true)
                                {
                                    valor = Convert.ToDecimal(smt.S_merc_tarif_tarifa_total) / Convert.ToDecimal(smt.Tipo_Room.Tipo_room_number);
                                }
                                else
                                {
                                    valor = Convert.ToDecimal(smt.S_merc_tarif_tarifa_total);
                                }

                                valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);
                                valorfinal = valorComCambio;
                            }
                            else
                            {
                                if (smt.S_merc_tarif_porApartamento == true)
                                {
                                    valorfinal = Convert.ToDecimal(smt.S_merc_tarif_tarifa_total) / Convert.ToDecimal(smt.Tipo_Room.Tipo_room_number);
                                }
                                else
                                {
                                    valorfinal = Convert.ToDecimal(smt.S_merc_tarif_tarifa_total);
                                }

                                //valorfinal = Convert.ToDecimal(smt.S_merc_tarif_tarifa_total);
                            }


                            if (smt != null)
                            {

                                AcertaValorTarifaCopia(Convert.ToDecimal(item.markup), Convert.ToDecimal(valorfinal),
                                                       Convert.ToDecimal(item.desconto), Convert.ToDecimal(item.markupNet),
                                                       Convert.ToDecimal(item.descontoNet), Convert.ToInt32(item.NumNoites),
                                                       Convert.ToInt32(item.Qtd_Tarifas));
                                valores = ViewState["ValoresCopiaVendNet_venda_total"].ToString().Split('/');
                            }
                            else
                            {
                                valores = new string[] { "0", "0", "0" };
                            }

                            filetarifas.S_merc_tarif_valor = valorfinal;
                            filetarifas.S_merc_tarif_vendaNet = Convert.ToDecimal(valores[0]);
                            filetarifas.S_merc_tarif_venda = Convert.ToDecimal(valores[1]);
                            filetarifas.S_merc_tarif_total = Convert.ToDecimal(valores[2]);
                        }
                        else
                        {
                            filetarifas.markup = 0;
                            filetarifas.markupNet = 0;
                            filetarifas.desconto = 0;
                            filetarifas.descontoNet = 0;
                            filetarifas.S_merc_tarif_vendaNet = 0;
                            filetarifas.S_merc_tarif_venda = 0;
                            filetarifas.S_merc_tarif_total = 0;
                            filetarifas.S_merc_tarif_valor = 0;
                        }
                    }


                    filetarifas.NomePacote = item.NomePacote;
                    filetarifas.S_nome = item.S_nome;
                    filetarifas.S_email = item.S_email;

                    filetarifas.S_id = item.S_id;
                    filetarifas.Categoria = item.Categoria;
                    filetarifas.Categoria_id = item.Categoria_id;
                    filetarifas.Room = item.Room;
                    filetarifas.Room_id = item.Room_id;
                    filetarifas.Moeda = item.Moeda;
                    filetarifas.Moeda_id = item.Moeda_id;
                    filetarifas.Status = item.Status;
                    filetarifas.FTC = item.FTC;
                    filetarifas.Valor_Conferir = item.Valor_Conferir;
                    filetarifas.Cambio = item.Cambio;
                    filetarifas.Cancelado = item.Cancelado;
                    filetarifas.Ordem = item.Ordem;

                    filetarifas.UpdVenda = item.UpdVenda;
                    filetarifas.Range_id = item.Range_id;

                    fttdao.Salvar(filetarifas);
                }

                FileTransfersDAL ftransfdao = new FileTransfersDAL();

                foreach (File_Transfers item in ftransfdao.ListarTodos(AntigoFileId))
                {

                    File_Transfers fileTransf = new File_Transfers();

                    DateTime from = Convert.ToDateTime(item.Data_From).AddDays(dias);
                    DateTime to = Convert.ToDateTime(item.Data_To).AddDays(dias);

                    fileTransf.File_id = fc.File_id;
                    fileTransf.Flights_id = item.Flights_id;
                    fileTransf.SubServico = item.SubServico;
                    fileTransf.Paxs = item.Paxs;
                    fileTransf.Paying_Pax = item.Paying_Pax;
                    fileTransf.Supp_Paying_Pax = item.Supp_Paying_Pax;
                    fileTransf.Data_From = from;
                    fileTransf.Data_To = to;

                    fileTransf.Qtd_Transf = item.Qtd_Transf;

                    fileTransf.markup = item.markup;
                    fileTransf.desconto = item.desconto;
                    fileTransf.markupNet = item.markupNet;
                    fileTransf.descontoNet = item.descontoNet;

                    int IdCidade;

                    if (item.Trf_CID_id != null) IdCidade = Convert.ToInt32(item.Trf_CID_id); else IdCidade = 0;

                    AcertaValorServicosCopia(Convert.ToDecimal(item.markup), Convert.ToDecimal(item.desconto),
                                             Convert.ToDecimal(item.markupNet), Convert.ToDecimal(item.descontoNet),
                                             Convert.ToBoolean(item.SubServico), Convert.ToInt32(item.S_id), item.Transf_nome, Convert.ToDateTime(from),
                                             Convert.ToDateTime(to), Convert.ToInt32(item.Paying_Pax),
                                             IdCidade, Convert.ToInt32(item.Paying_Pax));

                    string[] valores;

                    if (ViewState["ValoresCopiaServicoVendNet_venda_valor_total"].Equals(""))
                    {
                        valores = new string[] { "0", "0", "0", "0" };
                    }
                    else
                    {
                        valores = ViewState["ValoresCopiaServicoVendNet_venda_valor_total"].ToString().Split('/');
                    }


                    fileTransf.S_merc_tarif_vendaNet = Convert.ToDecimal(valores[0]);
                    fileTransf.Transf_vendaNet = Convert.ToDecimal(valores[0]);
                    fileTransf.Transf_venda = Convert.ToDecimal(valores[1]);
                    fileTransf.Transf_valor = Convert.ToDecimal(valores[2]);
                    fileTransf.Transf_total = Convert.ToDecimal(valores[3]);


                    fileTransf.S_nome = item.S_nome;
                    fileTransf.S_id = item.S_id;
                    fileTransf.Transf_nome = item.Transf_nome;
                    fileTransf.Transf_tipo = item.Transf_tipo;
                    fileTransf.Transf_tipo_categ = item.Transf_tipo_categ;
                    fileTransf.Moeda = item.Moeda;
                    fileTransf.Moeda_id = item.Moeda_id;
                    fileTransf.Trf_Tours = item.Trf_Tours;
                    fileTransf.Status = item.Status;
                    fileTransf.FTC = item.FTC;
                    fileTransf.Valor_Conferir = item.Valor_Conferir;
                    fileTransf.Cambio = item.Cambio;
                    fileTransf.Ordem = item.Ordem;
                    fileTransf.Cancelado = item.Cancelado;
                    fileTransf.UpdVenda = item.UpdVenda;
                    fileTransf.Trf_CID_id = item.Trf_CID_id;

                    ftransfdao.Salvar(fileTransf);
                }

                FileServExtraDAL fServExtdao = new FileServExtraDAL();

                foreach (File_ServExtra item in fServExtdao.ListarTodos(AntigoFileId))
                {

                    File_ServExtra fileServExtra = new File_ServExtra();

                    DateTime from = Convert.ToDateTime(item.Data_From).AddDays(dias);
                    DateTime to = Convert.ToDateTime(item.Data_To).AddDays(dias);

                    fileServExtra.File_id = fc.File_id;
                    fileServExtra.Flights_id = item.Flights_id;
                    fileServExtra.Paxs = item.Paxs;
                    fileServExtra.Paying_Pax = item.Paying_Pax;
                    fileServExtra.Supp_Paying_Pax = item.Supp_Paying_Pax;
                    fileServExtra.Data_From = from;
                    fileServExtra.Data_To = to;
                    fileServExtra.markup = item.markup;
                    fileServExtra.desconto = item.desconto;
                    fileServExtra.markupNet = item.markupNet;
                    fileServExtra.descontoNet = item.descontoNet;
                    fileServExtra.S_merc_tarif_vendaNet = item.S_merc_tarif_vendaNet;
                    fileServExtra.Qtd_ServExtr = item.Qtd_ServExtr;
                    fileServExtra.NumPaxs_ServExtr = item.NumPaxs_ServExtr;
                    fileServExtra.File_ServExtra_valor = item.File_ServExtra_valor;
                    fileServExtra.File_ServExtra_vendaNet = item.File_ServExtra_vendaNet;
                    fileServExtra.File_ServExtra_venda = item.File_ServExtra_venda;
                    fileServExtra.File_ServExtra_total = item.File_ServExtra_total;
                    fileServExtra.S_nome = item.S_nome;
                    fileServExtra.S_id = item.S_id;
                    fileServExtra.File_ServExtra_nome = item.File_ServExtra_nome;
                    fileServExtra.TipoServico = item.TipoServico;
                    fileServExtra.TipoServico_id = item.TipoServico_id;
                    fileServExtra.Moeda = item.Moeda;
                    fileServExtra.Moeda_id = item.Moeda_id;
                    fileServExtra.Status = item.Status;
                    fileServExtra.FTC = item.FTC;
                    fileServExtra.Valor_Conferir = item.Valor_Conferir;
                    fileServExtra.Cambio = item.Cambio;
                    fileServExtra.Ordem = item.Ordem;
                    fileServExtra.Cancelado = item.Cancelado;
                    fileServExtra.UpdVenda = item.UpdVenda;


                    fServExtdao.Salvar(fileServExtra);
                }


                lblNovoFileCopiado.Visible = true;
                lblNovoFileCopiado.Text = NovoFile;

                ModalPopupExtenderCopiarFile.Show();


            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void AcertaValorTarifaCopia(decimal markup, decimal valor, decimal desconto, decimal markupNet, decimal descontoNet, int numnoites, int paypax)
        {

            try
            {

                double venda = 0;

                if (Convert.ToDecimal(markup) < 1)
                {
                    venda = (Convert.ToDouble(valor) / Convert.ToDouble(markup));
                }
                else
                {
                    venda = (Convert.ToDouble(valor) * Convert.ToDouble(markup) / 100) + Convert.ToDouble(valor);
                }

                ArredondaDAL arrd = new ArredondaDAL();

                string[] pars = Convert.ToDecimal(venda).ToString().Split(',');
                decimal valorArr = 0;

                if (pars.Count() > 1)
                {
                    Arredonda arr;

                    if (pars[1].Length == 1)
                    {
                        string val = pars[1] + 0;
                        arr = arrd.ObterArr(Convert.ToInt32(val.Substring(0, 2)));
                    }
                    else
                    {
                        arr = arrd.ObterArr(Convert.ToInt32(pars[1].Substring(0, 2)));
                    }

                    if (arr.Arredonda_recebe < 1)
                    {
                        valorArr = Convert.ToDecimal(pars[0]) + Convert.ToDecimal(arr.Arredonda_recebe);
                        venda = Convert.ToDouble(valorArr);
                    }
                    else
                    {
                        valorArr = Convert.ToDecimal(pars[0]) + Convert.ToDecimal(arr.Arredonda_recebe);
                        venda = Convert.ToDouble(valorArr);
                    }
                }



                double addDesconto = venda - (venda * Convert.ToDouble(desconto) / 100);

                double addNrNoites = Convert.ToDouble(numnoites) * addDesconto;

                //txtVendaNet.Text = addNrNoites.ToString("N");

                double addMarkupNet = (Convert.ToDouble(addNrNoites) * Convert.ToDouble(markupNet) / 100) + Convert.ToDouble(addNrNoites);

                double addDescontoNet = addMarkupNet - (addMarkupNet * Convert.ToDouble(descontoNet) / 100);

                double multNet = Convert.ToDouble(paypax) * addDescontoNet;

                //txtVenda.Text = addDescontoNet.ToString("N");

                //lblValorTotalTarifas.Text = multNet.ToString("N");


                ViewState["ValoresCopiaVendNet_venda_total"] = addNrNoites + "/" + addDescontoNet + "/" + multNet;

                //File_Tarifas ft = new File_Tarifas();

                //ft.File_Tarifas_id = Convert.ToInt32(IdFileTarifa.Text);
                //ft.S_merc_tarif_vendaNet = Convert.ToDecimal(addNrNoites);
                //ft.S_merc_tarif_venda = Convert.ToDecimal(addDescontoNet);
                //ft.S_merc_tarif_total = Convert.ToDecimal(multNet);
                //ft.S_merc_tarif_valor = Convert.ToDecimal(txtValorTarifas.Text);
                //ft.markup = Convert.ToDecimal(txtMarkup.Text);
                //ft.markupNet = Convert.ToDecimal(txtMarkupNet.Text);
                //ft.desconto = Convert.ToDecimal(txtDesconto.Text);
                //ft.descontoNet = Convert.ToDecimal(txtDescontoNet.Text);
                //ft.Qtd_Tarifas = Convert.ToInt32(txtQtdTarifas.Text);

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void AcertaValorServicosCopia(decimal markup, decimal desconto, decimal markupNet, decimal descontoNet, bool SubServico, int IdSupplier, string trfNome, DateTime dtFrom, DateTime dtTo, int numRange, int IdCidade, int paypax)
        {
            try
            {
                SBaseValorDAL sbaseV = new SBaseValorDAL();
                MontaServicoDAL msd = new MontaServicoDAL();

                decimal valor = 0;
                decimal valorComCambio = 0;
                decimal valorTotal = 0;

                if (SubServico)
                {

                    Monta_Servico_Valores msvv = new Monta_Servico_Valores();
                    S_Bases_Valor sbv = sbaseV.ObterValorSub(Convert.ToInt32(IdSupplier),
                                                             trfNome,
                                                             Convert.ToDateTime(dtFrom),
                                                             Convert.ToDateTime(dtTo),
                                                             Convert.ToInt32(numRange));

                    if (sbv == null)
                    {
                        ViewState["ValoresCopiaServicoVendNet_venda_valor_total"] = "";
                        return;
                    }

                    if (sbv.S_Bases.Moeda_id != Convert.ToInt32(ddlMoeda.SelectedValue))
                    {
                        CambioDAL cambDal = new CambioDAL();

                        Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(sbv.S_Bases.Moeda_id), Convert.ToInt32(ddlMoeda.SelectedValue));

                        valor = Convert.ToDecimal(Convert.ToDecimal(sbv.S_Bases_Valor_valor));
                        valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                        valorTotal = valorComCambio;
                    }
                    else
                    {
                        valorTotal = Convert.ToDecimal(sbv.S_Bases_Valor_valor);
                    }

                    //valorTotal = Convert.ToDecimal(sbv.S_Bases_Valor_valor);
                    //IdMoeda = sbv.S_Bases.Moeda_id;
                    //tarifa = Convert.ToDecimal(sbv.S_Bases_Valor_valor);
                }
                else
                {
                    Monta_Servico_Valores msvv = new Monta_Servico_Valores();


                    if (IdCidade != 0)
                    {

                        msvv = msd.ObterValorTransfers(Convert.ToDateTime(dtFrom),
                                                                            Convert.ToDateTime(dtTo),
                                                                            Convert.ToInt32(IdSupplier),
                                                                            Convert.ToInt32(numRange),
                                                                            trfNome,
                                                                            Convert.ToInt32(IdCidade));
                    }
                    else
                    {
                        msvv = msd.ObterValorTransfers(Convert.ToDateTime(dtFrom),
                                                                             Convert.ToDateTime(dtTo),
                                                                             Convert.ToInt32(IdSupplier),
                                                                             Convert.ToInt32(numRange),
                                                                             trfNome);
                    }

                    if (msvv == null)
                    {
                        ViewState["ValoresCopiaServicoVendNet_venda_valor_total"] = "";
                        return;
                    }

                    if (msvv.S_Bases.Moeda_id != Convert.ToInt32(ddlMoeda.SelectedValue))
                    {
                        CambioDAL cambDal = new CambioDAL();

                        Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(msvv.S_Bases.Moeda_id), Convert.ToInt32(ddlMoeda.SelectedValue));

                        valor = Convert.ToDecimal(Convert.ToDecimal(msvv.MServico_Valores_Bulk_Total));
                        valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                        valorTotal = valorComCambio;
                    }
                    else
                    {
                        valorTotal = Convert.ToDecimal(msvv.MServico_Valores_Bulk_Total);
                    }

                    //valorTotal = Convert.ToDecimal(msvv.MServico_Valores_Bulk_Total);
                    //IdMoeda = msvv.S_Bases.Moeda_id;
                    //tarifa = Convert.ToDecimal(msvv.MServico_Valores_Bulk_Total);
                }

                double venda = 0;
                File_Transfers ft = new File_Transfers();

                if (Convert.ToDecimal(markup) < 1)
                {
                    venda = (Convert.ToDouble(valorTotal) / Convert.ToDouble(markup));
                }
                else
                {
                    venda = (Convert.ToDouble(valorTotal) * Convert.ToDouble(markup) / 100) + Convert.ToDouble(valorTotal);
                }

                if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                {
                    double addDesconto = venda - (venda * Convert.ToDouble(desconto) / 100);

                    double mult = Convert.ToDouble(paypax) * addDesconto;

                    //txtVendaNet.Text = addDesconto.ToString("N");

                    double addMarkupNet = (Convert.ToDouble(addDesconto) * Convert.ToDouble(markupNet) / 100) +
                                                                                            Convert.ToDouble(addDesconto);

                    double addDescontoNet = addMarkupNet - (addMarkupNet * Convert.ToDouble(descontoNet) / 100);

                    double multNet = Convert.ToDouble(paypax) * addDescontoNet;

                    ViewState["ValoresCopiaServicoVendNet_venda_valor_total"] = addDesconto + "/" + addDescontoNet + "/" + valorTotal + "/" + multNet;

                    //txtVenda.Text = addDescontoNet.ToString("N");

                    //lblValorTotalTarifas.Text = multNet.ToString("N");

                    //ft.File_Transf_id = Convert.ToInt32(IdFileTarifa.Text);
                    //ft.Transf_vendaNet = Convert.ToDecimal(addDesconto);
                    //ft.Transf_venda = Convert.ToDecimal(addDescontoNet);
                    //ft.Transf_total = Convert.ToDecimal(multNet);
                    //ft.markupNet = Convert.ToDecimal(txtMarkupNet.Text);
                    //ft.descontoNet = Convert.ToDecimal(txtDescontoNet.Text);
                }
                else
                {
                    double addDesconto = venda - (venda * Convert.ToDouble(desconto) / 100);

                    double mult = Convert.ToDouble(paypax) * addDesconto;

                    ViewState["ValoresCopiaServicoVendNet_venda_valor_total"] = addDesconto + "/" + addDesconto + "/" + valorTotal + "/" + mult;

                    //txtVendaNet.Text = addDesconto.ToString("N");
                    //txtVenda.Text = addDesconto.ToString("N");

                    //lblValorTotalTarifas.Text = mult.ToString("N");

                    //ft.File_Transf_id = Convert.ToInt32(IdFileTarifa.Text);
                    //ft.Transf_venda = Convert.ToDecimal(addDesconto);
                    //ft.Transf_vendaNet = Convert.ToDecimal(addDesconto);
                    //ft.Transf_total = Convert.ToDecimal(mult);
                    //ft.markupNet = 0;
                    //ft.descontoNet = 0;
                }


                //ft.Transf_valor = Convert.ToDecimal(txtValorTarifas.Text);
                //ft.markup = Convert.ToDecimal(txtMarkup.Text);
                //ft.desconto = Convert.ToDecimal(txtDesconto.Text);
                //ft.Qtd_Transf = Convert.ToInt32(txtQtdTarifas.Text);

                //ftd.Atualizar(ft);

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        #endregion

        #region Politica CHD

        protected void OpenPoliticaCHD_Command(object sender, CommandEventArgs e)
        {

            try
            {
                SPoliticaChdDAL spdal = new SPoliticaChdDAL();

                GridPoliticasCHDCadastro.DataSource = spdal.ListarTodos(Convert.ToInt32(e.CommandArgument));
                GridPoliticasCHDCadastro.DataBind();

                ModalPopupExtenderPoliticaChd.Show();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        #endregion

        #region Opts Quote

        protected void btnQuote1_Click(object sender, EventArgs e)
        {
            try
            {
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();

                VerificaAtivo(1);
                UpdatePanelFormInto.Update();

                ViewState["QuoteAtiva"] = 1;
                lblQA.Text = "1";

                Quotation q = fcd.RetornaQuoteObj(txtQuoteNumber.Text);

                if (q != null)
                {
                    Quotation_Grupo qg = qgd.ObterPorIdQuotation(q.Quotation_Id);
                    PopulaNewQuote(qg.Quotation_Grupo_Id, 1);
                }

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnQuote2_Click(object sender, EventArgs e)
        {
            try
            {
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                VerificaAtivo(2);
                UpdatePanelFormInto.Update();

                ViewState["QuoteAtiva"] = 2;
                lblQA.Text = "2";

                Quotation q = fcd.RetornaQuoteObj(txtQuoteNumber.Text);

                if (q != null)
                {
                    Quotation_Grupo qg = qgd.ObterPorIdQuotation(q.Quotation_Id);
                    PopulaNewQuote(qg.Quotation_Grupo_Id, 2);
                }


            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnQuote3_Click(object sender, EventArgs e)
        {
            try
            {
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                VerificaAtivo(3);
                UpdatePanelFormInto.Update();

                ViewState["QuoteAtiva"] = 3;
                lblQA.Text = "3";

                Quotation q = fcd.RetornaQuoteObj(txtQuoteNumber.Text);

                if (q != null)
                {
                    Quotation_Grupo qg = qgd.ObterPorIdQuotation(q.Quotation_Id);
                    PopulaNewQuote(qg.Quotation_Grupo_Id, 3);
                }
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnQuote4_Click(object sender, EventArgs e)
        {
            try
            {
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                VerificaAtivo(4);
                UpdatePanelFormInto.Update();

                ViewState["QuoteAtiva"] = 4;
                lblQA.Text = "4";

                Quotation q = fcd.RetornaQuoteObj(txtQuoteNumber.Text);

                if (q != null)
                {
                    Quotation_Grupo qg = qgd.ObterPorIdQuotation(q.Quotation_Id);
                    PopulaNewQuote(qg.Quotation_Grupo_Id, 4);
                }
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnQuote5_Click(object sender, EventArgs e)
        {
            try
            {
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                VerificaAtivo(5);
                UpdatePanelFormInto.Update();

                ViewState["QuoteAtiva"] = 5;
                lblQA.Text = "5";

                Quotation q = fcd.RetornaQuoteObj(txtQuoteNumber.Text);

                if (q != null)
                {
                    Quotation_Grupo qg = qgd.ObterPorIdQuotation(q.Quotation_Id);
                    PopulaNewQuote(qg.Quotation_Grupo_Id, 5);
                }
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnQuote6_Click(object sender, EventArgs e)
        {
            try
            {
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                VerificaAtivo(6);
                UpdatePanelFormInto.Update();

                ViewState["QuoteAtiva"] = 6;
                lblQA.Text = "6";

                Quotation q = fcd.RetornaQuoteObj(txtQuoteNumber.Text);

                if (q != null)
                {
                    Quotation_Grupo qg = qgd.ObterPorIdQuotation(q.Quotation_Id);
                    PopulaNewQuote(qg.Quotation_Grupo_Id, 6);
                }
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnQuote7_Click(object sender, EventArgs e)
        {
            try
            {
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                VerificaAtivo(7);
                UpdatePanelFormInto.Update();

                ViewState["QuoteAtiva"] = 7;
                lblQA.Text = "7";

                Quotation q = fcd.RetornaQuoteObj(txtQuoteNumber.Text);

                if (q != null)
                {
                    Quotation_Grupo qg = qgd.ObterPorIdQuotation(q.Quotation_Id);
                    PopulaNewQuote(qg.Quotation_Grupo_Id, 7);
                }
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnQuote8_Click(object sender, EventArgs e)
        {
            try
            {
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                VerificaAtivo(8);
                UpdatePanelFormInto.Update();

                ViewState["QuoteAtiva"] = 8;
                lblQA.Text = "8";

                Quotation q = fcd.RetornaQuoteObj(txtQuoteNumber.Text);

                if (q != null)
                {
                    Quotation_Grupo qg = qgd.ObterPorIdQuotation(q.Quotation_Id);
                    PopulaNewQuote(qg.Quotation_Grupo_Id, 8);
                }
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnQuote9_Click(object sender, EventArgs e)
        {
            try
            {
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                VerificaAtivo(9);
                UpdatePanelFormInto.Update();

                ViewState["QuoteAtiva"] = 9;
                lblQA.Text = "9";

                Quotation q = fcd.RetornaQuoteObj(txtQuoteNumber.Text);

                if (q != null)
                {
                    Quotation_Grupo qg = qgd.ObterPorIdQuotation(q.Quotation_Id);
                    PopulaNewQuote(qg.Quotation_Grupo_Id, 9);
                }
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnQuote10_Click(object sender, EventArgs e)
        {
            try
            {
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                VerificaAtivo(10);
                UpdatePanelFormInto.Update();

                ViewState["QuoteAtiva"] = 10;
                lblQA.Text = "10";

                Quotation q = fcd.RetornaQuoteObj(txtQuoteNumber.Text);

                if (q != null)
                {
                    Quotation_Grupo qg = qgd.ObterPorIdQuotation(q.Quotation_Id);
                    PopulaNewQuote(qg.Quotation_Grupo_Id, 10);
                }
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void VerificaAtivo(int Numero)
        {

            switch (Numero)
            {
                case 1:
                    lblQuoteAtiva.Text = "Quote ativa: Op 1";
                    break;
                case 2:
                    lblQuoteAtiva.Text = "Quote ativa: Op 2";
                    break;
                case 3:
                    lblQuoteAtiva.Text = "Quote ativa: Op 3";
                    break;
                case 4:
                    lblQuoteAtiva.Text = "Quote ativa: Op 4";
                    break;
                case 5:
                    lblQuoteAtiva.Text = "Quote ativa: Op 5";
                    break;
                case 6:
                    lblQuoteAtiva.Text = "Quote ativa: Op 6";
                    break;
                case 7:
                    lblQuoteAtiva.Text = "Quote ativa: Op 7";
                    break;
                case 8:
                    lblQuoteAtiva.Text = "Quote ativa: Op 8";
                    break;
                case 9:
                    lblQuoteAtiva.Text = "Quote ativa: Op 9";
                    break;
                case 10:
                    lblQuoteAtiva.Text = "Quote ativa: Op 10";
                    break;
            }
        }

        protected void VerificaOpts()
        {
            try
            {
                RangeDal rd = new RangeDal();
                Quotation q = new FileCarrinhoDAL().RetornaQuoteObj(txtQuoteNumber.Text);

                if (q != null)
                {
                    Array lista = rd.RetornaOpts(q.Quotation_Id);

                    for (int i = 0; i < lista.Length; i++)
                    {
                        switch (i)
                        {
                            case 1:
                                btnQuote2.Visible = true;
                                break;
                            case 2:
                                btnQuote3.Visible = true;
                                break;
                            case 3:
                                btnQuote4.Visible = true;
                                break;
                            case 4:
                                btnQuote5.Visible = true;
                                break;
                            case 5:
                                btnQuote6.Visible = true;
                                break;
                            case 6:
                                btnQuote7.Visible = true;
                                break;
                            case 7:
                                btnQuote8.Visible = true;
                                break;
                            case 8:
                                btnQuote9.Visible = true;
                                break;
                            case 9:
                                btnQuote10.Visible = true;
                                break;
                        }

                    }

                }

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnNomearOpts_Click(object sender, EventArgs e)
        {

            try
            {

                RangeDal rd = new RangeDal();
                Quotation q = new FileCarrinhoDAL().RetornaQuoteObj(txtQuoteNumber.Text);

                if (q != null)
                {
                    GridOptsFile.DataSource = rd.RetornaOptsFull(q.Quotation_Id);
                    GridOptsFile.DataBind();
                }

                ModalPopupExtenderAddNomeOpts.Show();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnSalvarNomeOpts_Click(object sender, EventArgs e)
        {
            try
            {
                RangeDal rd = new RangeDal();
                Quotation q = new FileCarrinhoDAL().RetornaQuoteObj(txtQuoteNumber.Text);
                List<Ranges> lista = new List<Ranges>();

                foreach (GridViewRow item in GridOptsFile.Rows)
                {
                    TextBox txtNomeOpcao = (TextBox)item.FindControl("txtNomeOpcao");
                    Label lblnum = (Label)item.FindControl("lblnum");

                    foreach (Ranges item2 in rd.ListarTodosOpts(q.Quotation_Id, Convert.ToInt32(lblnum.Text)))
                    {
                        Ranges r = new Ranges();
                        r.OptQuoteNome = txtNomeOpcao.Text;
                        r.Ranges_id = item2.Ranges_id;
                        lista.Add(r);
                    }

                    rd.AtualizaListOpts(lista);
                }

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnAddOpt_Click(object sender, EventArgs e)
        {
            try
            {

                RangeDal rd = new RangeDal();
                Quotation q = new FileCarrinhoDAL().RetornaQuoteObj(txtQuoteNumber.Text);
                Quotation_Grupo qg = new QuotationGrupoDAL().ObterPorIdQuotation(q.Quotation_Id);

                Array qtd = rd.RetornaOpts(q.Quotation_Id);

                int last = qtd.Length + 1;

                switch (last)
                {
                    case 2:
                        btnQuote2.Visible = true;
                        VerificaAtivo(2);
                        UpdatePanelFormInto.Update();
                        ViewState["QuoteAtiva"] = 2;
                        lblQA.Text = "2";
                        PopulaNewQuote(qg.Quotation_Grupo_Id, 2);
                        break;
                    case 3:
                        btnQuote3.Visible = true;
                        VerificaAtivo(3);
                        UpdatePanelFormInto.Update();
                        ViewState["QuoteAtiva"] = 3;
                        lblQA.Text = "3";
                        PopulaNewQuote(qg.Quotation_Grupo_Id, 3);
                        break;
                    case 4:
                        btnQuote4.Visible = true;
                        VerificaAtivo(4);
                        UpdatePanelFormInto.Update();
                        ViewState["QuoteAtiva"] = 4;
                        lblQA.Text = "4";
                        PopulaNewQuote(qg.Quotation_Grupo_Id, 4);
                        break;
                    case 5:
                        btnQuote5.Visible = true;
                        VerificaAtivo(5);
                        UpdatePanelFormInto.Update();
                        ViewState["QuoteAtiva"] = 5;
                        lblQA.Text = "5";
                        PopulaNewQuote(qg.Quotation_Grupo_Id, 5);
                        break;
                    case 6:
                        btnQuote6.Visible = true;
                        VerificaAtivo(6);
                        UpdatePanelFormInto.Update();
                        ViewState["QuoteAtiva"] = 6;
                        lblQA.Text = "6";
                        PopulaNewQuote(qg.Quotation_Grupo_Id, 6);
                        break;
                    case 7:
                        btnQuote7.Visible = true;
                        VerificaAtivo(7);
                        UpdatePanelFormInto.Update();
                        ViewState["QuoteAtiva"] = 7;
                        lblQA.Text = "7";
                        PopulaNewQuote(qg.Quotation_Grupo_Id, 7);
                        break;
                    case 8:
                        btnQuote8.Visible = true;
                        VerificaAtivo(8);
                        UpdatePanelFormInto.Update();
                        ViewState["QuoteAtiva"] = 8;
                        lblQA.Text = "8";
                        PopulaNewQuote(qg.Quotation_Grupo_Id, 8);
                        break;
                    case 9:
                        btnQuote9.Visible = true;
                        VerificaAtivo(9);
                        UpdatePanelFormInto.Update();
                        ViewState["QuoteAtiva"] = 9;
                        lblQA.Text = "9";
                        PopulaNewQuote(qg.Quotation_Grupo_Id, 9);
                        break;
                    case 10:
                        btnQuote10.Visible = true;
                        VerificaAtivo(10);
                        UpdatePanelFormInto.Update();
                        ViewState["QuoteAtiva"] = 10;
                        lblQA.Text = "10";
                        PopulaNewQuote(qg.Quotation_Grupo_Id, 10);
                        break;
                }

                if (GridBasesTarifas.Rows.Count == 0)
                {
                    ModalPopupExtenderSelectFileCopia.Show();
                }

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnSelectFileCopia_Click(object sender, EventArgs e)
        {
            try
            {
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                QuotationDAL qd = new QuotationDAL();
                QuotationGrupoDAL qgd = new QuotationGrupoDAL();

                FileTarifasDAL ftd = new FileTarifasDAL();
                FileTransfersDAL ftrd = new FileTransfersDAL();
                FileServExtraDAL fsed = new FileServExtraDAL();

                RangeDal rd = new RangeDal();

                Quotation q = qd.ObterPorCode(txtAutoSelectFileCopia.Text);
                Quotation_Grupo qg = qgd.ObterPorIdQuotation(q.Quotation_Id);

                int idFile = fcd.RetornaFileID(Convert.ToInt32(qg.Quotation_Grupo_Id));
                int IdQuote = qg.Quotation_Id;

                foreach (File_Tarifas item in ftd.ListarTodosOpt(idFile, Convert.ToInt32(ddlOptSelectFileCopia.SelectedValue)))
                {
                    File_Tarifas ft2 = new File_Tarifas();

                    ft2.File_id = idFile;
                    ft2.Flights_id = item.Flights_id;
                    ft2.Paxs = item.Paxs;
                    ft2.Paying_Pax = item.Paying_Pax;
                    ft2.Supp_Paying_Pax = item.Supp_Paying_Pax;
                    ft2.Data_From = item.Data_From;
                    ft2.Data_To = item.Data_To;

                    ft2.NumNoites = item.NumNoites;
                    ft2.Qtd_Tarifas = item.Qtd_Tarifas;
                    ft2.S_meal_nome = item.S_meal_nome;
                    ft2.S_meal_status = item.S_meal_status;
                    ft2.Meal = item.Meal;
                    ft2.S_meal_id = item.S_meal_id;
                    ft2.NomePacote = item.NomePacote;
                    ft2.S_nome = item.S_nome;
                    ft2.S_email = item.S_email;
                    ft2.S_id = item.S_id;
                    ft2.Categoria = item.Categoria;
                    ft2.Categoria_id = item.Categoria_id;
                    ft2.Room = item.Room;
                    ft2.Room_id = item.Room_id;
                    ft2.Moeda = item.Moeda;
                    ft2.Moeda_id = item.Moeda_id;
                    ft2.Status = item.Status;
                    ft2.FTC = item.FTC;
                    ft2.Valor_Conferir = item.Valor_Conferir;
                    ft2.Cambio = item.Cambio;
                    ft2.Cancelado = item.Cancelado;
                    ft2.Ordem = item.Ordem;
                    ft2.NomePacote = item.NomePacote;
                    ft2.GeraFile = item.GeraFile;
                    ft2.FdsFrom = item.FdsFrom;
                    ft2.FdsTo = item.FdsTo;
                    ft2.TBulk = item.TBulk;
                    ft2.UpdVenda = item.UpdVenda;
                    ft2.Range_id = item.Range_id;
                    ft2.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);
                    ft2.OptQuoteNome = item.OptQuoteNome;

                    ftd.Salvar(ft2);

                    int idLastRange = 0;

                    foreach (Ranges itemRang in rd.ListarTodos(IdQuote, Convert.ToInt32(ddlOptSelectFileCopia.SelectedValue), item.File_Tarifas_id, "hotel"))
                    {
                        Ranges r = new Ranges();

                        r.Ranges_de = itemRang.Ranges_de;
                        r.Ranges_ate = itemRang.Ranges_ate;
                        r.Quotation_Id = IdQuote;
                        r.Flag = itemRang.Flag;
                        r.FileTabelaId = ft2.File_Tarifas_id;
                        r.markup = itemRang.markup;
                        r.desconto = itemRang.desconto;
                        r.markupNet = itemRang.markupNet;
                        r.descontoNet = itemRang.descontoNet;
                        r.VendaNet = itemRang.VendaNet;
                        r.Valor = itemRang.Valor;
                        r.Venda = itemRang.Venda;
                        r.ValorTotal = itemRang.ValorTotal;
                        r.Ordem = itemRang.Ordem;

                        r.QtdTC = itemRang.QtdTC;
                        r.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                        if (r.Ranges_de.Equals("TC"))
                        {
                            r.RangeID = idLastRange;
                            idLastRange = 0;
                        }

                        rd.Salvar(r);

                        if (!r.Ranges_de.Equals("TC"))
                        {
                            idLastRange = r.Ranges_id;
                        }
                    }

                }


                foreach (File_Transfers item in ftrd.ListarTodosOpt(idFile, Convert.ToInt32(ddlOptSelectFileCopia.SelectedValue)))
                {
                    File_Transfers ft2 = new File_Transfers();

                    ft2.File_id = idFile;
                    ft2.Flights_id = item.Flights_id;
                    ft2.SubServico = item.SubServico;
                    ft2.Paxs = item.Paxs;
                    ft2.Paying_Pax = item.Paying_Pax;
                    ft2.Supp_Paying_Pax = item.Supp_Paying_Pax;
                    ft2.Data_From = item.Data_From;
                    ft2.Data_To = item.Data_To;
                    ft2.Qtd_Transf = item.Qtd_Transf;
                    ft2.S_nome = item.S_nome;
                    ft2.S_id = item.S_id;
                    ft2.Transf_nome = item.Transf_nome;
                    ft2.Transf_tipo = item.Transf_tipo;
                    ft2.Transf_tipo_categ = item.Transf_tipo_categ;
                    ft2.Moeda = item.Moeda;
                    ft2.Moeda_id = item.Moeda_id;
                    ft2.Trf_Tours = item.Trf_Tours;
                    ft2.Status = item.Status;
                    ft2.FTC = item.FTC;
                    ft2.Valor_Conferir = item.Valor_Conferir;
                    ft2.Cambio = item.Cambio;
                    ft2.Cancelado = item.Cancelado;
                    ft2.Ordem = item.Ordem;
                    ft2.TBulk = item.TBulk;
                    ft2.Trf_CID_id = item.Trf_CID_id;
                    ft2.UpdVenda = item.UpdVenda;
                    ft2.Range_id = item.Range_id;
                    ft2.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);
                    ft2.OptQuoteNome = item.OptQuoteNome;

                    ftrd.Salvar(ft2);

                    int idLastRange = 0;

                    foreach (Ranges itemRang in rd.ListarTodos(IdQuote, Convert.ToInt32(ddlOptSelectFileCopia.SelectedValue), item.File_Transf_id, "servico"))
                    {
                        Ranges r = new Ranges();

                        r.Ranges_de = itemRang.Ranges_de;
                        r.Ranges_ate = itemRang.Ranges_ate;
                        r.Quotation_Id = IdQuote;
                        r.Flag = itemRang.Flag;
                        r.FileTabelaId = ft2.File_Transf_id;
                        r.markup = itemRang.markup;
                        r.desconto = itemRang.desconto;
                        r.markupNet = itemRang.markupNet;
                        r.descontoNet = itemRang.descontoNet;
                        r.VendaNet = itemRang.VendaNet;
                        r.Valor = itemRang.Valor;
                        r.Venda = itemRang.Venda;
                        r.ValorTotal = itemRang.ValorTotal;
                        r.Ordem = itemRang.Ordem;

                        r.QtdTC = itemRang.QtdTC;
                        r.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                        if (r.Ranges_de.Equals("TC"))
                        {
                            r.RangeID = idLastRange;
                            idLastRange = 0;
                        }

                        rd.Salvar(r);

                        if (!r.Ranges_de.Equals("TC"))
                        {
                            idLastRange = r.Ranges_id;
                        }
                    }

                }


                foreach (File_ServExtra item in fsed.ListarTodosOpt(idFile, Convert.ToInt32(ddlOptSelectFileCopia.SelectedValue)))
                {
                    File_ServExtra ft2 = new File_ServExtra();

                    ft2.File_id = idFile;
                    ft2.Flights_id = item.Flights_id;
                    ft2.Paxs = item.Paxs;
                    ft2.Paying_Pax = item.Paying_Pax;
                    ft2.Supp_Paying_Pax = item.Supp_Paying_Pax;
                    ft2.Data_From = item.Data_From;
                    ft2.Data_To = item.Data_To;
                    ft2.Qtd_ServExtr = item.Qtd_ServExtr;
                    ft2.S_nome = item.S_nome;
                    ft2.S_id = ft2.S_id;
                    ft2.NumPaxs_ServExtr = item.NumPaxs_ServExtr;
                    ft2.S_id = item.S_id;
                    ft2.File_ServExtra_nome = item.File_ServExtra_nome;
                    ft2.TipoServico = item.TipoServico;
                    ft2.TipoServico_id = item.TipoServico_id;
                    ft2.Moeda = item.Moeda;
                    ft2.Moeda_id = item.Moeda_id;
                    ft2.Status = item.Status;
                    ft2.FTC = item.FTC;
                    ft2.Valor_Conferir = item.Valor_Conferir;
                    ft2.Cambio = item.Cambio;
                    ft2.Cancelado = item.Cancelado;
                    ft2.Ordem = item.Ordem;
                    ft2.TBulk = item.TBulk;
                    ft2.UpdVenda = item.UpdVenda;
                    ft2.Range_id = item.Range_id;
                    ft2.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);
                    ft2.OptQuoteNome = item.OptQuoteNome;

                    fsed.Salvar(ft2);

                    int idLastRange = 0;

                    foreach (Ranges itemRang in rd.ListarTodos(IdQuote, Convert.ToInt32(ddlOptSelectFileCopia.SelectedValue), item.File_ServExtra_id, "extra"))
                    {
                        Ranges r = new Ranges();

                        r.Ranges_de = itemRang.Ranges_de;
                        r.Ranges_ate = itemRang.Ranges_ate;
                        r.Quotation_Id = IdQuote;
                        r.Flag = itemRang.Flag;
                        r.FileTabelaId = ft2.File_ServExtra_id;
                        r.markup = itemRang.markup;
                        r.desconto = itemRang.desconto;
                        r.markupNet = itemRang.markupNet;
                        r.descontoNet = itemRang.descontoNet;
                        r.VendaNet = itemRang.VendaNet;
                        r.Valor = itemRang.Valor;
                        r.Venda = itemRang.Venda;
                        r.ValorTotal = itemRang.ValorTotal;
                        r.Ordem = itemRang.Ordem;

                        r.QtdTC = itemRang.QtdTC;
                        r.OptQuote = Convert.ToInt32(ViewState["QuoteAtiva"]);

                        if (r.Ranges_de.Equals("TC"))
                        {
                            r.RangeID = idLastRange;
                            idLastRange = 0;
                        }

                        rd.Salvar(r);

                        if (!r.Ranges_de.Equals("TC"))
                        {
                            idLastRange = r.Ranges_id;
                        }
                    }

                }

                PopulaNewQuote(qg.Quotation_Grupo_Id, Convert.ToInt32(ViewState["QuoteAtiva"]));
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnSelectFileCopiaNCopia_Click(object sender, EventArgs e)
        {
            //VerificaAtivo();
            ModalPopupExtenderSelectFileCopia.Hide();
        }

        protected void ddlUsuarioSelectFileCopia_SelectedIndexChanged(object sender, EventArgs e)
        {
            ModalPopupExtenderSelectFileCopia.Show();
        }

        protected void ddlClienteSelectFileCopia_SelectedIndexChanged(object sender, EventArgs e)
        {
            ModalPopupExtenderSelectFileCopia.Show();
        }

        #endregion

        #region Markup

        protected void btnAddMarkup_Click(object sender, EventArgs e)
        {
            try
            {
                ModalPopupExtenderMarkupFile.Show();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void PopularGridMarkup(int IdQuotGrupo)
        {
            try
            {
                GridMarkup.DataSource = new MarkupFileDAL().LisarPorQuot(IdQuotGrupo);
                GridMarkup.DataBind();
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void EditarMarkup(object sender, CommandEventArgs e)
        {
            try
            {
                int myid = Convert.ToInt32(e.CommandArgument);

                BuscaMarkup(myid);

                TabContainerMarkup.ActiveTab = tabCadastro;
                TabContainerMarkup.Visible = true;
                TabContainerMarkup.ActiveTabIndex = 1;

                ModalPopupExtenderMarkupFile.Show();
            }
            catch (Exception ex)
            {
                lblMsgCadMarkup.Text = ex.Message;
            }
        }

        protected void BuscaMarkup(int IdMarkup)
        {
            try
            {

                btnNovoMarkup.Text = "Novo";

                MarkupFileDAL cmd = new MarkupFileDAL();
                MarkupFile cm = cmd.ObterPorId(IdMarkup);

                txtCodMarkup.Text = cm.MarkupFile_id.ToString();
                txtDataInicialMarkup.Text = string.Format("{0:dd/MM/yyyy}", cm.MarkupFile_dataInicial);
                txtDataFinalMarkup.Text = string.Format("{0:dd/MM/yyyy}", cm.MarkupFile_dataFinal);
                txtMarkupHotel.Text = cm.MarkupFile_hotel.ToString();
                txtMarkupDescHotel.Text = cm.MarkupFile_descontoHotel.ToString();
                txtMarkupServico.Text = cm.MarkupFile_servico.ToString();
                txtMarkupDescServico.Text = cm.MarkupFile_descontoServico.ToString();
                txtMarkupSeasonal.Text = cm.MarkupFile_seasonal.ToString();
                txtMarkupMeal.Text = cm.MarkupFile_meals.ToString();


            }
            catch (Exception ex)
            {
                lblMsgCadMarkup.Text = ex.Message;
            }
        }

        protected void ExcluirMarkup(object sender, CommandEventArgs e)
        {
            try
            {
                int myid = Convert.ToInt32(e.CommandArgument);

                MarkupFileDAL cmd = new MarkupFileDAL();
                MarkupFile cm = cmd.ObterPorId(myid);
                cmd.Excluir(cm);
                MostrarMsg("Registro excluído com sucesso.");
                PopularGridMarkup(Convert.ToInt32(ViewState["IdQuotGrupo"]));
            }
            catch (Exception ex)
            {
                lblMsgCadMarkup.Text = ex.Message;
            }
        }

        protected void AtualizarMarkup(object sender, EventArgs e)
        {
            try
            {
                MarkupFileDAL cmd = new MarkupFileDAL();

                Utils ut = new Utils();

                MarkupFile cm = new MarkupFile();

                cm.MarkupFile_id = Convert.ToInt32(txtCodMarkup.Text);
                cm.MarkupFile_dataInicial = Convert.ToDateTime(txtDataInicialMarkup.Text);
                cm.MarkupFile_dataFinal = Convert.ToDateTime(txtDataFinalMarkup.Text);
                cm.MarkupFile_hotel = Convert.ToDecimal(ut.pMoneyToIMoney(txtMarkupHotel.Text));
                cm.MarkupFile_descontoHotel = Convert.ToDecimal(txtMarkupDescHotel.Text);
                cm.MarkupFile_servico = Convert.ToDecimal(txtMarkupServico.Text);
                cm.MarkupFile_descontoServico = Convert.ToDecimal(txtMarkupDescServico.Text);
                cm.MarkupFile_seasonal = Convert.ToDecimal(Retorna(txtMarkupSeasonal.Text));
                cm.MarkupFile_meals = Convert.ToDecimal(Retorna(txtMarkupMeal.Text));

                cmd.Atualizar(cm);

                MostrarMsg("Registro atualizado com sucesso.");

                LimparMarkup();

                PopularGridMarkup(Convert.ToInt32(ViewState["IdQuotGrupo"]));

                ModalPopupExtenderMarkupFile.Show();
            }
            catch (Exception ex)
            {
                lblMsgCadMarkup.Text = ex.Message;
            }
        }

        protected void SalvarMarkup(object sender, EventArgs e)
        {
            try
            {

                if (txtCodMarkup.Text != "")
                {
                    LimparMarkup();
                    lblMsgCadMarkup.Text = "";
                    txtDataInicialMarkup.Focus();
                    btnNovoMarkup.Text = "Salvar";
                    ModalPopupExtenderMarkupFile.Show();
                    return;
                }

                MarkupFileDAL cmd = new MarkupFileDAL();
                Utils ut = new Utils();
                MarkupFile cm = new MarkupFile();

                cm.MarkupFile_dataInicial = Convert.ToDateTime(txtDataInicialMarkup.Text);
                cm.MarkupFile_dataFinal = Convert.ToDateTime(txtDataFinalMarkup.Text);
                cm.MarkupFile_hotel = Convert.ToDecimal(ut.pMoneyToIMoney(txtMarkupHotel.Text));
                cm.MarkupFile_descontoHotel = Convert.ToDecimal(txtMarkupDescHotel.Text);
                cm.MarkupFile_servico = Convert.ToDecimal(txtMarkupServico.Text);
                cm.MarkupFile_descontoServico = Convert.ToDecimal(txtMarkupDescServico.Text);
                cm.MarkupFile_seasonal = Convert.ToDecimal(Retorna(txtMarkupSeasonal.Text));
                cm.MarkupFile_meals = Convert.ToDecimal(Retorna(txtMarkupMeal.Text));
                cm.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);

                cmd.Salvar(cm);
                MostrarMsg("Registro cadastrado com sucesso.");
                LimparMarkup();

                PopularGridMarkup(Convert.ToInt32(ViewState["IdQuotGrupo"]));

                ModalPopupExtenderMarkupFile.Show();
            }
            catch (Exception ex)
            {
                lblMsgCadMarkup.Text = ex.Message;
            }
        }

        protected string Retorna(string valor)
        {
            if (valor.Equals(""))
            {
                return null;
            }
            else
            {
                return valor;
            }
        }

        protected void LimparMarkup()
        {
            txtCodMarkup.Text = "";
            txtDataInicialMarkup.Text = "";
            txtDataFinalMarkup.Text = "";
            txtMarkupHotel.Text = "";
            txtMarkupDescHotel.Text = "";
            txtMarkupServico.Text = "";
            txtMarkupDescServico.Text = "";
            txtMarkupSeasonal.Text = "";
            txtMarkupMeal.Text = "";
        }

        #endregion

        #region Rooming

        protected void btnSalvarRooming_Click(object sender, EventArgs e)
        {
            try
            {
                RoomingListDAL rld = new RoomingListDAL();
                RoomingList r = new RoomingList();
                RoomingList rr = rld.ObterPorQuote(Convert.ToInt32(ViewState["IdQuotGrupo"]));
                if (rr != null)
                {
                    r.rooming_text = txtRoomingList.Text.Trim();
                    r.rooming_id = rr.rooming_id;
                    rld.Atualizar(r);

                    MostrarMsg("Registro atualizado com sucesso.");
                }
                else
                {
                    r.rooming_text = txtRoomingList.Text.Trim();
                    r.Quotation_Grupo_Id = Convert.ToInt32(ViewState["IdQuotGrupo"]);
                    rld.Salvar(r);
                    MostrarMsg("Registro cadastrado com sucesso.");
                }
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void RetornaRooming()
        {
            try
            {
                RoomingList txt = new RoomingListDAL().ObterPorQuote(Convert.ToInt32(ViewState["IdQuotGrupo"]));

                if (txt != null)
                {
                    txtRoomingList.Text = txt.rooming_text;
                }
                else
                {
                    txtRoomingList.Text = "";
                }

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        #endregion

        #region Pacote

        protected void btnGerarPacote_Click(object sender, EventArgs e)
        {
            try
            {

                PacoteDAL pacd = new PacoteDAL();
                SupplierDAL sppd = new SupplierDAL();
                ServicoDAL servDal = new ServicoDAL();
                FileServExtraDAL fsed = new FileServExtraDAL();

                Pacote paccode = pacd.RetornaLast();
                //string CodePacote = "Pkg1";
                string CodePacote = "";
                int randomNumber = 0;

                //if (paccode != null)
                //{
                Random random = new Random();
                randomNumber = random.Next(0, 100000);

                while (pacd.ListarTodos("Pkg" + randomNumber.ToString(), "").Count > 0)
                {
                    randomNumber = random.Next(0, 100000);
                }

                CodePacote = "Pkg" + randomNumber;
                //}               

                foreach (GridViewRow item in GridBasesTarifas.Rows)
                {
                    Pacote pacnew = new Pacote();
                    Label lblFlag = (Label)item.FindControl("lblFlag");
                    Label lblIdRetorna = (Label)item.FindControl("lblIdRetorna");


                    switch (lblFlag.Text)
                    {
                        case "hotel":

                            File_Tarifas qt = new FileTarifasDAL().ObterPorId(Convert.ToInt32(lblIdRetorna.Text));

                            pacnew.Pacote_Code = CodePacote;
                            pacnew.Pacote_Quote = txtQuoteNumber.Text;
                            pacnew.SuppNome = qt.S_nome;

                            if (Convert.ToBoolean(qt.Meal))
                            {
                                pacnew.Flag = "MEAL";

                                if (qt.S_meal_status != null)
                                {
                                    pacnew.MealNome = qt.S_meal_nome + " " + qt.S_meal_status;
                                }
                                else
                                {
                                    pacnew.MealNome = qt.S_meal_nome;
                                }
                            }
                            else
                            {
                                pacnew.Room = qt.Room;
                                pacnew.Categoria = qt.Categoria;
                                pacnew.Flag = "HOTEL";
                            }

                            pacnew.S_id = qt.S_id;
                            pacnew.Ordem = qt.Ordem;

                            Supplier sp = sppd.ObterPorId(Convert.ToInt32(qt.S_id));

                            pacnew.Cidade = sp.Cidade.CID_nome;

                            pacd.Salvar(pacnew);

                            break;

                        case "servico":

                            File_Transfers qtr = new FileTransfersDAL().ObterPorId(Convert.ToInt32(lblIdRetorna.Text));

                            pacnew.Pacote_Code = CodePacote;
                            pacnew.Pacote_Quote = txtQuoteNumber.Text;
                            pacnew.ServNome = qtr.Transf_nome;
                            pacnew.S_id = qtr.S_id;
                            pacnew.Ordem = qtr.Ordem;

                            if (qtr.SubServico != null)
                            {
                                pacnew.Flag = "SubServ";
                            }
                            else if (qtr.Trf_Tours.Equals("TRF"))
                            {
                                pacnew.Flag = "TRANSFER";
                            }
                            else
                            {
                                pacnew.Flag = "TOUR";

                            }

                            S_Servicos ss;

                            if (qtr.Trf_CID_id != null)
                            {
                                ss = servDal.ObterPorNome(qtr.Transf_nome.Trim(), Convert.ToInt32(qtr.Trf_CID_id));
                            }
                            else
                            {
                                ss = servDal.ObterPorNome(qtr.Transf_nome.Trim());
                            }

                            pacnew.Cidade = ss.Cidade.CID_nome;

                            pacd.Salvar(pacnew);

                            break;

                        case "extra":

                            File_ServExtra qserv = new FileServExtraDAL().ObterPorId(Convert.ToInt32(lblIdRetorna.Text));

                            pacnew.Pacote_Code = CodePacote;
                            pacnew.Pacote_Quote = txtQuoteNumber.Text;
                            pacnew.ServExtraNome = qserv.File_ServExtra_nome;
                            pacnew.Flag = "EXTRA";
                            pacnew.S_id = qserv.S_id;
                            pacnew.Ordem = qserv.Ordem;

                            Supplier sp2 = sppd.ObterPorId(Convert.ToInt32(qserv.S_id));
                            pacnew.Cidade = sp2.Cidade.CID_nome;

                            pacd.Salvar(pacnew);

                            break;
                    }


                }

                lblPkgCode.Text = CodePacote;

                ModalPopupExtenderGeraPacoteFim.Show();

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void btnSalvarPacote_Click(object sender, EventArgs e)
        {
            try
            {
                PacoteDAL pd = new PacoteDAL();

                foreach (Pacote item in pd.ListarTodos(lblPkgCode.Text, ""))
                {
                    Pacote pac = new Pacote();

                    pac.DataFrom = Convert.ToDateTime(txtDataFromPacote.Text);
                    pac.DataTo = Convert.ToDateTime(txtDataToPacote.Text);
                    pac.Pacote_NomePacote = txtNomePacote.Text;
                    pac.Pacote_id = item.Pacote_id;

                    pd.Atualizar(pac);
                }

                MostrarMsg("Pacote gerado com sucesso.");
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        #endregion

        protected void MostrarMsg(string Msg)
        {
            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "showAutoCloseMessage('" + Msg + "')", true);
        }

    }
}